Post on 21-Jan-2016
description
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
UNIT III- RMI And EJB
RMI- Overview – RMI Architecture - Developing Application with RMI Declaring and
implementing remote interfaces –Stub and Skleton –registering Remote objects – writing
RMI server –client- EJB Introduction Entity bean –session bean –EJB Transaction
RMI Definition
The Java Remote Method Invocation system allows an object running in one Java virtual machine to
invoke methods on an object running in another Java virtual machine. RMI provides for remote
communication between programs written in the Java programming language
RMI is a core package of the JDK 1.1 and above that can be used to develop distributed application. It
enables software developers to write distributed applications in which the methods of remote objects can
be invoked from other JVMs
The RMI system architecture
The RMI system is built in three layers
• The stub/skeleton layer
• The remote reference layer
• The transport layer
The Stub and Skeleton
• A client invokes a remote method; the call is first forwarded to stub.
• The stub is responsible for sending the remote call over to the server-side skeleton
• The stub opening a socket to the remote server, assemble the object parameters and forwarding
the data stream to the skeleton.
• A skeleton contains a method that receives the remote calls, unassemble the parameters, and
invokes the actual remote object implementation.
Stu
b
RMI Client RMI Server
skele
ton
return
call
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
The remote reference layer:
The remote reference layer is a middle layer between the stub/skeleton layer and the transport layer. This
layer is responsible for providing the ability to support varying remote reference or invocation protocols
independent of the client stubs and server skeletons.
The Transport layer
• The transport layer is the low-layer that ships assemble streams between different address spaces.
The transport layer is responsible for setting up connections to remote address spaces, managing
connections, listening for incoming calls, maintaining a table of remote objects that reside in the
same address space, setting up a connections to this dispatcher.
Steps for Developing an RMI System
1. Define the remote interface
2. Develop the remote object by implementing the remote interface.
3. Develop the client program.
4. Compile the Java source files.
5. Generate the client stubs and server skeletons.
6. Start the RMI registry.
7. Start the remote server objects.
8. Run the client
Step 1: Defining the Remote Interface:
• To create an RMI application, the first step is the defining of a remote interface between the client
and server objects.
/* SampleServer.java */
import java.rmi.*;
public interface SampleServer extends Remote
{ public int sum(int a,int b) throws RemoteException;
}
Step 2: Develop the remote object and its interface
• The server is a simple unicast remote server.
• Create server by extending java.rmi.server.UnicastRemoteObject.
• The server uses the RMISecurityManager to protect its resources while engaging in remote
communication.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
/* SampleServerImpl.java */
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
public class SampleServerImpl extends UnicastRemoteObject implements SampleServer
{ SampleServerImpl() throws RemoteException {
super(); }
/* SampleServerImpl.java */
public static void main(String args[])
{ try {
System.setSecurityManager(new RMISecurityManager());
//set the security manager
//create a local instance of the object
SampleServerImpl Server = new SampleServerImpl();
//put the local instance in the registry
Naming.rebind("SAMPLE-SERVER" , Server);
System.out.println("Server waiting.....");
}
catch (java.net.MalformedURLException me) {
System.out.println("Malformed URL: " + me.toString()); }
catch (RemoteException re) {
System.out.println("Remote exception: " + re.toString()); }
}
Step 3: Develop the client program
import java.rmi.*;
import java.rmi.server.*;
public class SampleClient
{
public static void main(String[] args)
{ // set the security manager for the client
System.setSecurityManager(new RMISecurityManager());
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
//get the remote object from the registry
try
{
System.out.println("Security Manager loaded");
String url = "//localhost/SAMPLE-SERVER";
SampleServer remoteObject = (SampleServer)Naming.lookup(url);
System.out.println("Got remote object");
System.out.println(" 1 + 2 = " + remoteObject.sum(1,2) );
}
catch (RemoteException exc) {
System.out.println("Error in lookup: " + exc.toString()); }
catch (java.net.MalformedURLException exc) {
System.out.println("Malformed URL: " + exc.toString()); }
catch (java.rmi.NotBoundException exc) {
System.out.println("NotBound: " + exc.toString());
} } }
Step 4 & 5: Compile the Java source files & Generate the client stubs and server skeletons
• Assume the program compile and executing at elpis on ~/rmi
• Once the interface is completed, you need to generate stubs and skeleton code. The RMI system
provides an RMI compiler (rmic) that takes your generated interface class and procedures stub
code on its self.
elpis:~/rmi> set CLASSPATH=‖~/rmi‖
elpis:~/rmi> javac SampleServer.java
elpis:~/rmi> javac SampleServerImpl.java
elpis:~/rmi> rmic SampleServerImpl
elpis:~/rmi> javac SampleClient.java
Step 6: Start the RMI registry
• The RMI applications need install to Registry. And the Registry must start manual by call
rmiregisty.
• The rmiregistry us uses port 1099 by default. You can also bind rmiregistry to a different port by
indicating the new port number as : rmiregistry <new port>
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
elpis:~/rmi> rmiregistry
• Remark: On Windows, you have to type in from the command line:
> start rmiregistry
Steps 7 & 8: Start the remote server objects & Run the client
• Once the Registry is started, the server can be started and will be able to store itself in the
Registry.
• Because of the grained security model in Java 2.0, you must setup a security policy for RMI by
set java.security.policy to the file policy.all
elpis:~/rmi> java –Djava.security.policy=policy.all SampleServerImpl
elpis:~/rmi> java –Djava.security.policy=policy.all SampleClient
Distributed Garbage Collection
When stand-alone applications are developed using java, objects that are no longer referenced by
any client are automatically deleted. This is a desirable feature when developing distributed
applications. The RMI system provides a distributed garbage collector that automatically deletes
remote objects that are no longer referenced by any client.
Security
There are a number of security issues that you should be aware of when developing
mission-critical systems in RMI.
• There is no authentication; a client just requests and object (stub), and the server supplies it.
Subsequent communication is assumed to b from the same client.
• There is no access control to the objects
• There are no security checks on the RMI registry itself; any caller Is allowed to make request.
• There is no version control between the stubs and the skeletons, making it possible for client to
use a down-level stub to access a more recent skeleton breaking release-to-release binary
compatibility
Conclusion
• RMI is an alternative to low level sockets
• RMI is a core package of the JDK 1.1 and above that can be used to develop distributed
application.
• The RMI system is built in three layers The stub/skeleton layer, The remote reference layer, The
transport layer
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Enterprise beans are the Java EE server side components that run inside the ejb container and
encapsulates the business logic of an enterprise application. Enterprise applications are the software
applications developed intended to use at large scale. These applications involves large number of data
accessing concurrently by many users.
A middleware component model for Java and CORBA
(Common Object Request Broker Architecture)
• Presented by Sun in the 1999, they are easier than other technologies as RMI
Introduction
• This is the three level structure for Application Server
Application Server
• Presentation
• Business Logic
• Data Access
Presentation layer
• HTML
– Generated server-side HTML
– Runs on any Web browser
– Less client-side power
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
• Java
– Required Java virtual Machine
– More client side power
– Runned on a page
– Security (Applet)
– Launched from a browser or a standalone application
Business Logic:
• Implements the logic of the application defining all the function that may be used from a client
– Change Business Rules Easily
– Re-use components
– Make complex applications manageable
– Secure Data hiding
Data Access:
• Utility to access external datas such as Database or other Web component
• Access other SOA
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
J2EE Application Server:
• Java 2 Enterprise Edition standardizes interfaces for Application Server components
EJB Properties:
• Bean writers need not write
– Remote access Protocols
– Transactional Behaviour
– Threads
– Security
– State Management
– Object life cycle
– Persistence
EJB Overview:
When to use Enterprise bean:
• Applications developed by using the enterprise beans deal with a variety of clients, simply by
writing few lines of code, so that the client can locate the enterprise beans. The client locating the
enterprise bean may be various, numerous and thin.
• Enterprise beans support transaction to ensure the integrity of the database. Transaction is the
mechanism of managing the concurrent access of shared objects.
• Managing the fast growing number of users requires distributed application components across
multiple machines means that the application must be scalable.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Type of beans
• Session Bean
• Entity Bean
• Message Driven Bean
Session Bean:
• Represents a single client inside the server
• The client calls the session bean to invoke methods of an application on the server
• Perform works for its client, hiding the complexity of interaction with other objects in the server
• Is not shared
• Is not persistent
• When the client stops the session,the bean can be assigned to another client from the server
• Unique to each client
Session Bean:
• Stateful session bean
• Stateless session bean
Stateful Session Bean
• Contains the state of a single client session:
– Information on the client
– On method called
– Return values
This state is called conversational state and is not retained when the session ends, also if the client not
removes the bean
- Remembers previous request, and response of session
Entity Bean
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Represents a business object in a persistent storage mechanism such as a relational database
Usually is a table in the database and each instance of that entity bean is a row in that table
Properties:
Persistent
Allow shared access
Have primary key
Have relationship with other entity beans.
Auto commit.
EJB Example:
The example has three component:
– Services: what the client can do in the system such as see the foreign currency , listed
shares or make operations on his hown account.
– Accounts: a database containing the accounts of all the clients of the bank with
information about credit,debit,access etc..
– Security: is a subsystem that receives all the alarm caused from wrong access and
performs action about the situation
( calls police and stops operation of that client keeping information about him )
• In this example is easy to create an EJB structure.
– Client will have a web page at client side to insert values and connect the system.This
will be done using JSP ( Java Servlet Pages )
– Services will be a Statefull Session Bean and it will be different for each client
connecting the system mantaining data about the client connected.
– Accounts will be formed by an Entity Bean for each account in the system with a code-
account as primary key.
– Security will be a Message driven bean and will be called only from container if some
operation are abnormal for result or the autentification for the same client fails too much
times.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
UNIT –IV JDBC
JDBC/ODBC Driver – Connection Procedure with Example - SQL: DDL,DML,TCL –
JDBC ResultSet- Metadata - ResultSetMetaData - JDBC Statements
JDBC
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
JDBC Architecture:
Common JDBC Components:
The JDBC API provides the following interfaces and classes:
DriverManager: This interface manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication
subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
Driver: This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager objects,
which manages objects of this type. It also abstracts the details associated with working
with Driver objects
Connection : Interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through
connection object only.
Statement : You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
ResultSet: These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its data.
SQLException: This class handles any errors that occur in a database application.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
JDBC Basics – Java Database Connectivity Steps
1. Loading a database driver.
The driver class by calling Class.forName() with the Driver class name as an argument.
Once loaded, the Driver class creates an instance of itself. A client can connect to Database
Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore
JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is ―Class‖. Class is a class in
java.lang package.
try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
}
catch(Exception x){
System.out.println( “Unable to load the driver class!” );
}
2. Creating a oracle jdbc Connection
` The JDBC DriverManager class defines objects which can
connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC
architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its
getConnection() method is used to establish a connection to a database. It uses a username, password, and
a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection
represents a session/connection with a specific database. Within the context of a Connection, SQL,
PL/SQL statements are executed and results are returned. An application can have one or more
connections with a single database, or it can have many connections with different databases.
try{
Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}
catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}
3. Creating a jdbc Statement object
Once a connection is obtained we can interact with the database. Connection interface
defines methods for interacting with the database via the established connection. To execute SQL
statements, you need to instantiate a Statement object from your connection object by using the
createStatement() method.
Statement statement = dbConnection.createStatement();
A statement object is used to send and execute SQL statements to a database.
4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Statement interface defines methods that are used to interact with database via the execution of
SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute().
Example:
import java.sql.*;
public class jdbc1
{
public static void main(String args[])
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con =
DriverManager.getConnection("jdbc:odbc:test");
Statement stat = con.createStatement(); stat.executeUpdate("create table emp(no int,name varchar(10))");
stat.executeUpdate("insert into emp values(1,'aaa')");
stat.executeUpdate("insert into emp values(2,'bbb')");
stat.executeUpdate("insert into emp values(3,'ccc')");
ResultSet rs = stat.executeQuery("select * from emp");
while(rs.next()) { int no = rs.getInt(1);
String name = rs.getString(2);
System.out.println(no + "\t" + name);
System.out.println();
} con.close();
} catch(Exception e)
{ e.printStackTrace+();
} }}
JDBC Driver Types
JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Type 1 JDBC Driver
JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a
generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other
alternative is available.
Type 1: JDBC-ODBC Bridge
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database’s ODBC drivers are already
available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and
this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
Type 2 JDBC Driver
Native-API/partly Java driver
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific
calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are
shown below. Example: Oracle will have oracle native api.
Type 2: Native api/ Partly Java Driver
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the
JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.
Type 3 JDBC Driver
All Java/Net-protocol driver
Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates
the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Type 3: All Java/ Net-Protocol Driver
Advantage
1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on),
load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the recordset may take longer, since the data
comes through the backend server.
Type 4 JDBC Driver
Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database server.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Type 4: Native-protocol/all-Java driver
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform
independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don’t have to translate database requests to
ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite
good.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded
dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
ResultSet and Cursors
The rows that satisfy a particular query are called the result set. The number of rows returned in a result
set can be zero or more. A user can access the data in a result set using a cursor one row at a time from
top to bottom. A cursor can be thought of as a pointer to the rows of the result set that has the ability to
keep track of which row is currently being accessed. The JDBC API supports a cursor to move both
forward and backward and also allowing it to move to a specified row or to a row whose position is
relative to another row
Types of Result Sets
TYPE_FORWARD_ONLY — the result set is not scrollable i.e. the cursor moves only
forward, from before the first row to after the last row.
TYPE_SCROLL_INSENSITIVE — the result set is scrollable; its cursor can move both
forward and backward relative to the current position,
and it can move to an absolute position.
TYPE_SCROLL_SENSITIVE — the result set is scrollable; its cursor can move both
forward and backward relative to the current position, and it can move to an absolute position.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Result Set Methods
When a ResultSet object is first created, the cursor is positioned before the first row. To move the cursor,
you can use the following methods:
next() – moves the cursor forward one row. Returns true if the cursor is now positioned on a row and
false if the cursor is positioned after the last row.
previous() – moves the cursor backwards one row. Returns true if the cursor is now positioned on a row
and false if the cursor is positioned before the first row.
first() – moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now
positioned on the first row and false if the ResultSet object does not contain any rows.
last() – moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now
positioned on the last row and false if the ResultSet objectdoes not contain any rows.
beforeFirst() – positions the cursor at the start of the ResultSet object, before the first row. If the
ResultSet object does not contain any rows, this method has no effect.
afterLast() – positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet
object does not contain any rows, this method has no effect.
relative(int rows) – moves the cursor relative to its current position.
absolute(int n) – positions the cursor on the n-th row of the ResultSet object.
Transaction Management
Transaction is a complete task which is a combination of the smaller tasks. For the major task to
be completed, the smaller tasks need to be successfully completed. If anyone task fails then all
the previous tasks are reverted to the original state.
For example if you are withdrawing money it consist getting money, reducing the balance from
account and also printing a slip. If anything gets failed then all the things should be converted to
its previous state. In order to achieve this type of functionality where all the queries should be
completed otherwise the task should be rolled back is acheieve by three methods
rollback(),
commit()
and setAutoCommit().
By default the connection commits all the changes once it is done with the single query. This can
be stopped by calling setAutoCommit(false) on connection object. Now for every transaction
user has to explicitly call commit() method only the changes get reflected otherwise changes
wont be shown in the database. Rollback() method gets called for withdrawing all the changes
done by the queries in the database.
Note:- The program will not change any data as the commit() is called after rollback().
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BasicTransactionExample {
public static void main(String[] args) {
try {
/** Loading the driver*/
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver ");
/** Getting Connection*/
Connection con =
DriverManager.getConnection("jdbc:odbc:Bank","mca","manager ");
/** Creating Statement*/
con.setAutoCommit(false);
Statement stmt= con.createStatement();
stmt.execute("delete from visualbuilder");
//Commits the transaction
System.out.println("Commit called ");
con.rollback();
con.commit();
stmt.close();
con.close();
}
catch (Exception e)
{ e.printStackTrace();
}
}}
UNIT –V JSP
Introduction to JSP - JSP life cycle - Attributes in JSP - JSP elements - Directives -
Declarations - Expressions - Script let - Action Elements - using session Object and
Cookies-Working with Java Mail - usage of use Bean Tag.
javaServer Pages
JavaServer Pages (JSP) is a server-side programming technology that enables the creation of
dynamic, platform-independent method for building Web-based applications like enterprise,
mission critical web applications such as e-commerce, banking and corporate intranet
applications.
Using JSP, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Advantages of JSP:
Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having a separate CGI files.
JSP are always compiled before it's processed by the server unlike CGI/Perl which requires
the server to load an interpreter and the target script each time the page is requested.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
It is portable to other operating systems and non-Microsoft Web servers.
• Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML.
• Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for
"real" programs that use form data, make database connections, and the like.
• JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image
processing etc.
JSP – Architecture
JSP Processing
The JSP container is responsible for intercepting requests for JSP pages
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by
using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in
which all template text is converted to println( ) statements and all JSP elements are converted to Java code that
implements the corresponding dynamic behavior of the page.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the
servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP
response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were
a static page.
Life cycle they follow.
A JSP life cycle can be defined as the entire process from its creation till the destruction which is
similar to a servlet life cycle with an additional step which is required to compile a JSP into
servlet.
The following are the paths followed by a JSP
Compilation
Initialization
Execution
Cleanup
JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the
page. If the page has never been compiled, or if the JSP has been modified since it was last
compiled, the JSP engine compiles the page.
The compilation process involves three steps:
1. Parsing the JSP.
2. Turning the JSP into a servlet.
3. Compiling the servlet.
(2) JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If
you need to perform JSP-specific initialization, override the jspInit() method:
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
public void jspInit()
{
// Initialization code...
}
Typically initialization is performed only once and as with the servlet init method, you generally
initialize database connections, open files, and create lookup tables in the jspInit method.
(3) JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its
parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response)
{
// Service handling code...
}
The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also responsible for generating
responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
(4) JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by
a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or
closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
// Your cleanup code goes here.
}
The Scriptlet
<% code fragment %>
<html>
<head><title>Hello World</title></head>
<body>
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code later in
the JSP file. You must declare the variable or method before you use it in the JSP file
<%! declaration; [ declaration; ]+ ... %>
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
JSP Expression:
A JSP expression element contains a scripting language expression that is evaluated, converted
to a String, and inserted where the expression appears in the JSP file
<%= expression %>
<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
JSP Comments:
<%-- This is JSP comment --%>
Here are a small number of special constructs you can use in various cases to insert comments or
characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
<%-- comment --%> A JSP comment. Ignored by the JSP engine.
<!-- comment --> An HTML comment. Ignored by the browser.
<\% Represents static <% literal.
%\> Represents static %> literal.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
\' A single quote in an attribute that uses single quotes.
\" A double quote in an attribute that uses double quotes.
JSP Directives:
The page directive is used to provide instructions to the container that pertain to the current JSP
page. You may code page directives anywhere in your JSP page. By convention, page directives
are coded at the top of the JSP page.
<%@ directive attribute="value" %>
There are three types of directive tag:
Directive Description
<%@ page ... %> Defines page-dependent attributes, such as scripting
language, error page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in
the page
The page Directive:
The page directive is used to provide instructions to the container that pertain to the current JSP
page. You may code page directives anywhere in your JSP page. By convention, page directives
are coded at the top of the JSP page.
Following is the basic syntax of page directive:
<%@ page attribute="value" %>
They include Directive:
They include directive is used to includes a file during the translation phase. This directive tells
the container to merge the content of other external files with the current JSP during the
translation phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="relative url" >
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
The filename in the include directive is actually a relative URL. If you just specify a filename
with no associated path, the JSP compiler assumes that the file is in the same directory as your
JSP.
The taglib Directive:
The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML
tags and a tag library is a set of user-defined tags that implement custom behavior.
The taglib directive declares that your JSP page uses a set of custom tags, identifies the location
of the library, and provides a means for identifying the custom tags in your JSP page.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
Where the uri attribute value resolves to a location the container understands and
the prefixattribute informs a container what bits of markup are custom actions.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
Using java Bean in JSP
Java Beans are reusable components. They are used to separate Business logic from the
Presentation logic. Internally, a bean is just an instance of a class
SP?s provide three basic tags for working with Beans.
<jsp:useBean id=?bean name? class=?bean class? scope = ?page | request | session
|application ?/>
bean name = the name that refers to the bean.
Bean class = name of the java class that defines the bean.
<jsp:setProperty name = ?id? property = ?someProperty? value = ?someValue? />
id = the name of the bean as specified in the useBean tag.
property = name of the property to be passed to the bean.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
value = value of that particular property .
An variant for this tag is the property attribute can be replaced by an ? * ?. What this does is that
it accepts all the form parameters and thus reduces the need for writing multiple setProperty tags.
The only consideration is that the form parameter names should be the same as that of the bean
property names.
<jsp:getProperty name = ?id? property = ?someProperty? />
Here the property is the name of the property whose value is to be obtained from the bean.
Example:
<%= new java.util.Date() %>
JSP Cookies
Cookies are short pieces of data sent by web servers to the client browser. The cookies are saved
to clients hard disk in the form of small text file. Cookies help the web servers to identify web
users, by this way server tracks the user. Cookies pay very important role in the session tracking.
Cookie Class
In JSP cookie are the object of the class javax.servlet.http.Cookie. This class is used to creates a
cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser,
and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are
commonly used for session management. A cookie has a name, a single value, and optional
attributes such as a comment, path and domain qualifiers, a maximum age, and a version
number.
The getCookies() method of the request object returns an array of Cookie objects. Cookies can
be constructed using the following code:
Method Description
getComment() Returns the comment describing the purpose of this cookie, or null if no such comment has been
defined.
getMaxAge() Returns the maximum specified age of the cookie.
getName() Returns the name of the cookie.
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
getPath() Returns the prefix of all URLs for which this cookie is targeted.
getValue() Returns the value of the cookie.
setComment(String) If a web browser presents this cookie to a user, the cookie's purpose will be described using this
comment.
setMaxAge(int)
Sets the maximum age of the cookie. The cookie will expire after that many seconds have
passed. Negative values indicate the default behavior: the cookie is not stored persistently, and
will be deleted when the user web browser exits. A zero value causes the cookie to be deleted
setPath(String) This cookie should be presented only with requests beginning with this URL.
setValue(String)
Sets the value of the cookie. Values with various special characters (white space, brackets and
parentheses, the equals sign, comma, double quote, slashes, question marks, the "at" sign, colon,
and semicolon) should be avoided. Empty values may not behave the same way on all browsers.
Cookies Exapme
<%@ page language="java" %>
<html>
<head>
<title>Cookie Input Form</title>
</head>
<body>
<form method="post" action="setcookie.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
</body>
<%@ page language="java" import="java.util.*"%>
<%
String username=request.getParameter("username");
if(username==null) username="";
Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
%>
<html>
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
<head>
<title>Cookie Saved</title>
</head>
<body>
<p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p>
</body>
Session Management
The Http protocol is a stateless protocol, that means that it can't persist the data. Http treats each
request as a new request so every time you will send a request you will be considered as a new
user. It is not reliable when we are doing any type of transactions or any other related work
where persistence of the information is necessary. To remove these obstacles we use session
management.JSP makes use of servlet provided HttpSession Interface which provides a way to
identify a user across more than one page request or visit to a Web site and to store information
about that user.
Syntax: <%@ page session="false" %>
Jsp design Page(index.jsp)
<html> <body>
<form method = "post" action = "FirstPageOfSession.jsp">
<font size = 6>Enter your name<input type = "text" name = "name"></font><br><br>
<font size = 6>Enter your password<input type="password" name = "pwd" >
</font><br><br>
<input type = "submit" name = "submit" value = "submit" >
</form>
</body>
</html>
Session (FirstPageOfSession.jsp) <%
String name = request.getParameter("name");
String password = request.getParameter("pwd");
if(name.equals("Williams") && password.equals("abcde"))
{
session.setAttribute("username",name);
response.sendRedirect("NextPageAfterFirst.jsp");
}
else
{ response.sendRedirect("SessionManagement.html");
}
%>
Created by K.Dharmarajan M.Sc.,M.Phil., www. professordharma.webs.com
Java Mail.
To be able to send e-mail, you need access to an "SMTP server". SMTP stands for "Simple Mail
Transfer Protocol". Most of the email on the internet is sent using SMTP servers.
If your email address is "you@yourhost.com", then there is a good chance your SMTP server is
either "yourhost.com" or something like "mail.yourhost.com" or "smtp.yourhost.com". You need
to find out exactly what it is. Your email program should have a "Settings" page which shows
you the name of your SMTP server (perhaps shown as "mail server" or "outgoing mail server".)