0% found this document useful (0 votes)
9 views

JEE E Content Unit III JSP23

Uploaded by

riaz ahamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

JEE E Content Unit III JSP23

Uploaded by

riaz ahamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

JEE_UNIT_III_JSP_E_CONTENT

P.G. Department of Computer Science (Shift – II)

M.Sc COMPUTER SCIENCE

E-Content

Subject : JEE(JAVA ENTERPRISE EDITION)


Class : I MSc COMPUTER SCIENCE
Unit : II(JSP,JAVAMAIL,JMS)
Assistant Professor : H.RIAZ AHAMED

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

UNIT-III: JSP
Introduction -Examining MVC and JSP -JSP scripting elements & directives-
Working with variables scopes-Error Pages - using Java Beans in JSP -Working
with Java Mail- Understanding Protocols in JavaMail-Components-JavaMail API-
Integrating into JEE-Understanding Java Messaging Services-Transactions.

JAVA SERVER PAGES

3.1 Introduction

JavaServer Page (JSP)—JavaServer Pages are “HTML-like” documents that


contain Java code. A JSP container compiles a JSP into a Servlet the first time
the page is requested.

3.2 Examining MVC and JSP

Model-View-Controller When developing a user interface, it is very important


to separate common responsibilities into separate objects. The most common
division of responsibility is known as Model-View-Controller (MVC) paradigm,
more accurately termed Presentation-Abstraction-Controller (PAC). The
components are:

• The Model (Abstraction) represents the underlying application objects that


access the database, represent business logic, etc. These objects are typically
JavaBeans, EJBs, or regular Java classes.

• The View (Presentation) is responsible for rendering the display. Typically


this is a JSP that uses helper objects, data objects, and custom tag libraries.

• The Controller is responsible for controlling application flow and mediating


between the abstraction and presentation layers. The controller is typically a
Servlet.

The client accesses the controller (Servlet) as the main page, or as the target
action of a form submission. The controller in turn accesses the underlying
business logic and database code of the abstraction layer and sets various data
and helper objects into scoped attributes on the Servlet (JavaBeans, EJBs, Java
classes). Finally, the request is redirected to the appropriate view (JSP) using
RequestDispatcher.forward().

3.3 JSP Scripting Elements and Directives


JSP elements (tags) can by grouped according to the functions they perform. For
example, they can be referred to as variable declarations, expressions, page

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

attributes, and so on. The tags are surrounded by angle brackets (<>), and like
HTML and XML tags can have attributes. Everything else that can be contained in
the JSP page but that cannot be known to the JSP translators (plain text, HTML
tags, and so on) is called template data.

The following are the various scripting elements used in JSP.

✦ Declarations
✦ Expressions
✦ Directives
✦ Scriptlets
✦ Comments
✦ Actions
✦ Implicit JSP objects
✦ Error pages
✦ JavaBeans

3.3.1 Declarations
JSP declarations are equivalent to member variables and functions of a class.
The declared variables and methods are accessible throughout the JSP. These
declarations are identified by using <%! %> or the XML equivalent
<jsp:declaration></jsp:declaration> tags.

Example:
<%! int balance = 0; %>
<%! public int getAccountBalance() {
return balance;
} %>
<jsp:declaration> int balance = 0; </jsp:declaration>
<jsp:declaration>
public int getAccountBalance()
{
return balance;
}
</jsp:declaration>

3.3.2 Expressions
An expression is an instruction to the web container to execute the code within
the expression and replace it with the results in the outputted content. Anything
placed inside of the <%= and %> tags is first evaluated and then inserted in the
final output. It’s XML equivalent is <jsp:expression> </jsp:expression> tags.

Example:
<% double salary=50000;%>
Your New Salary is <%=salary * 1.2%>

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

3.3.3 Scriptlets
A Scriptlet is a piece of Java code embedded in HTML that represents processing
logic to generate and display the dynamic content where ever needed in the
page. Scriptlets are declared using the <% %> script tags, or the
<jsp:scriptlet> </jsp:scriptlet> XML equivalents.

Example:
<% for (int n=0; n<10; n++)
{
out.println(n);
}
%>

3.3.4 Directives
Directives are instructions from the JSP to the container that can be used to set
the page properties, to import Java classes and packages, and to include
external web pages and custom tag libraries. The three directives are:

• page —the page directive sets the attributes of the page and provides the
functionality for importing Java classes. The page directive has eleven different
attributes that control everything from the scripting language to the classes and
packages imported into the page.

The general syntax for using a page directive is

<%@ page attribute1="value1" attribute2="value2" ...%>

Example:
<%@ page import="java.util.Date, java.io.*" extends="myJSPpage"
buffer="32k" autoflush="false" %>

• include— This directive enables to import the contents of another file into the
current JSP page.

<%@ include file="/legal/disclaimer.html">

• Taglib — the Taglib directive is used for Custom Tag Libraries. This directive
allows the JSP page to use custom tags written in Java. Custom tag definitions
are usually defined in a separate file called as Tag Library Descriptor. For the
current JSP to use a custom tag, it needs to import the tag library file which is
why this directive is used.

Syntax: <%@ taglib uri=”location of definition file” prefix=”prefix name” %>

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

3.3.5 Actions
Actions instruct the container to perform specific tasks at runtime. These actions
range from forwarding control to another page to generating a new Java Bean
for use in the page. The four types of actions are:

• forward — This action transfers control to a new web page.

• include— The include action temporarily transfers control to a new page,


performs the actions on the page, includes the output in the original page, and
returns control to the original page.

• Beans—Bean actions allow creation and use of JavaBeans inside a JSP. The
bean actions are explained in the Forms, JavaBeans, and JSP topic.

• Plug-in—The <jsp:plugin> action is used for working with Java applets.


Applets are client-side programs that run on a browser.

A page can be included at compile-time or at runtime. When including a file at


compile-time, the file's contents are inserted into the JSP code before it's
compiled into a servlet. When including a file at runtime, the JSP page will not
include the file until it has been compiled and receives a request.

If it is to include a file at compile-time, then use the JSP include directive. This
method of including files is generally more efficient and should be used
whenever the included file is relatively static and does not change much. Here's
what the include directive looks like:

<%@ include file="myFile.html" %>

Including Files at Runtime


Sometimes, to include some content that may change more frequently than a
static page header. One problem with using the include directive to include
frequently changing files is that some servlet engines will fail to recognize when
an included file has been modified and will not recompile the JSP. The solution to
this problem is to include the file at runtime instead.

Example: <jsp:include page="myContent.jsp" flush="true"/>

The flush attribute tells the servlet engine to flush the output buffer before
including the file.

3.3.6 Implicit Objects


The JSP container provides access to a set of implicit objects. These objects are
extensions of common Servlet components and provide some of the basic tools
necessary to build real applications with JSP.

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

✦ request—This variable points at HttpServletRequest. The following example


gets the flight destination entered by the user on the HTML page: <% String
dest= request.getParameter(“destination”); %>

✦ response—Use this variable to access the HttpServletResponse object.


Example: <% response.setContentType(“text/html”); %>

✦ out—This variable represents the JspWriter class, which has the same
functionality as the PrintWriter class in servlets.
Example: <% out.println(“Enter flight destination”); %>

✦ session—This variable represents the instance of the HTTPSession object.

✦ exception—This variable represents an instance of the uncaught Throwable


object and contains error information. This variable is only available from the
JSP error page that contains the directive isErrorPage=true.

✦ page—This variable represents the instance of the JSP’s Java class processing
the current request.

✦ pageContext—This variable represents the javax.servlet.jsp. PageContext


class, which contains methods for dealing with scoped data.

✦ application—This variable gives access to the ServletContext object without


having to call getServletConfig().getContext().

✦ config—This variable provides access to the ServletConfig object.

3.4 Working with Variable Scopes


The Scope of an object in JSP describes how widely it is available and who has
access it.

(i) Page Scope: Objects with page scope are accessible only within the page in
which they are created.

<jsp:useBean id=“employee” class=”class name” scope=”page”/>

(ii) Request scope: Objects with request scope are accessible from pages
processing the same request in which they are created.

<jsp:useBean id=“employee” class=”class name” scope=”request”/>

(iii) Session scope: Objects with session scope are accessible from pages
processing requests that are in the same session as the one in which they are
created.

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

<jsp:useBean id=“employee” class=”class name” scope=”session”/>

(iv) Application scope: Objects with application scope are accessible from JSP
pages that reside in the same application. This creates a global object that is
available to all pages.

<jsp:useBean id=“employee” class=”class name” scope=”application”/>

2.5 Error Pages


In Java Server Pages (JSP), there are two types of errors. The first type of error
comes at translation or compilation time when JSP page is translated from JSP
source file to Java Servlet class file. The second type of JSP error which is called a
request time error occurs during run time or request time. These run time errors
result in the form of exception. Exception Handling is the process to handle
runtime errors.

One way to perform exception handling in JSP is the use of errorPage and
isErrorPage attributes of page directive

errorPage attribute
The errorPage attribute of page directive is used to specify the name of error
page that handles the exception. The error page contains the exception handling
code description for a particular page.

The syntax of this attribute is as follows:

<%@ page errorPage=”relative URL” %>

index.html
<form action="process.jsp">
Enter the first Number:<input type="text" name="n1">
Enter the second Number:<input type="text" name="n2">
<input type="submit" value="Calculate">
</form>

process.jsp
<%@page errorPage="error.jsp" %>
<% String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.println("Division of number is:"+c);
%>

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

isErrorPage attribute
The isErrorPage attribute indicates whether or not the current page can act as the
error page for another JSP page.

Use of isErrorPage takes one of the following two forms:

<%@ page isErrorPage="true" %>


<%@ page isErrorPage="false" %>
<%!-- Default --%>

error.jsp
<form action="index.jsp">
<%@page isErrorPage="true"%>
Sorry, an Exception has occured!
Exception is <%=exception %>
<input type="submit" value="Re-Compute">
</form>

3.6 Java Beans in JSP


Java beans used in JSP offer lot of flexibility and avoid duplicate business logic.
JSP technology uses standard actions for working with beans.

Following are the three standard actions for working with Java beans:

a. <jsp:useBean>
b. <jsp:setProperty>
c. <jsp:getProperty>

a. jsp:useBean
This action is used by the web container to instantiate a Java Bean or locates an
existing bean. The web container then assigns the bean to an id which the JSP
can use to work with it. The Java Bean is usually stored or retrieved in and from
the specified scope.

The syntax for this action is shown below:

<jsp:useBean id=“employee” class=”class name” scope=”scope name”/>

where ,id : A unique identifier that references the instance of the bean
class : Fully qualified name of the bean class
scope : The attribute that defines where the bean will be stored or
retrieved from; can be request or session (widely used)

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

If the scope is session, then the bean will be available to all the requests made
by the client in the same session. If the scope is request, then the bean will only
be available for the current request only.

b. jsp:setProperty
This action as the name suggests is used to populate the bean properties in the
specified scope.

Following is the syntax for this action.


<jsp:setProperty name =“employee” property ="propertyname" value=
"data"/>

For instance, if we need to populate a bean whose property is firstName with a


value John we use this action as shown below:

<jsp:setProperty name "cus" property ="firstName" value= "John" />

c. jsp:getProperty
This standard action is used to retrieve a specified property from a bean in a
specified scope. Following is how we can use this action to retrieve the value of
firstName property in a bean identified by cus in the session scope.

<jsp:getProperty name=”cus” property=”firstName” scope=”session”


/>

3.7 JavaMail
The JavaMail is an API that is used to compose, write and read electronic
messages (emails).

• The JavaMail API provides protocol-independent and platform-


independent framework for sending and receiving mails.

• The javax.mail and javax.mail.activation packages contains the core


classes of JavaMail API.

• The JavaMail facility can be applied to many events. It can be used at


the time of registering the user (sending notification such as thanks for
your interest to my site), forgot password (sending password to the
users email id), sending notifications for important updates etc. So
there can be various usage of java mail api.

3.7.1 Understanding Protocols in JavaMail


The protocols that underpin the workings of electronic mail are well established
and very mature.

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

The following are the core protocol implementations are bundled as part of the
JavaMail distribution.

SMTP
SMTP is an acronym for Simple Mail Transfer Protocol. It was first proposed back
in 1982 and was designed for the delivery of mail messages to servers.

POP
POP is an acronym for Post Office Protocol, also known as POP3. It provides a
mechanism the mechanism by which the majority of people collect their e-mail.
It is then the responsibility of the user to take care of the e-mail by filing it in
some logical storage. It provides support for single mail box for each user. The
POP server does not offer any storage facilities beyond the mailbox that new
mail is delivered to.

IMAP
IMAP is an acronym for Internet Message Access Protocol. IMAP is an advanced
protocol for receiving messages. It provides support for multiple mail box for
each user, in addition to, mailbox can be shared by multiple users. It is defined
in RFC 2060.

IMAP is a communication protocol used between the user and the server and is
only responsible for the reading and retrieval of messages. It is not used for the
delivery of e-mail between servers.

MIME
Multiple Internet Mail Extension (MIME) tells the browser what is being sent e.g.
attachment, format of the messages etc. It is not known as mail transfer
protocol but it is used by the mail program.

NNTP and Others


There are many protocols that are provided by third-party providers. Some of
them are Network News Transfer Protocol (NNTP), Secure Multipurpose Internet
Mail Extensions (S/MIME) etc.

3.8 JavaMail Components


The JavaMail API contains four major components:

✦ Session management—The session aspect of the API defines the interaction


the mail client has with the network. It handles all aspects associated with the
overall communication, including the protocol to use for transfer and any default
values that may be required. JavaMail has the javax.mail.Session class that
defines the mail session used for communicating with remote mail systems.

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

✦ Message manipulation—. This abstract class javax.mail.Message provides


the basic container for the representation of a mail message. A mail message is
made up of two major components, a header and some content.

The Message class implements the javax.mail.Part interface, which deals with
the functionality associated with constructing the header and the content.

✦ Mail storage and retrieval—JavaMail provides the management of


messages and also used for the handling of groups of messages. If a message
isn’t being sent or received, it is in storage. Messages are stored in hierarchies
that are not unlike those of files and directories. The JavaMail API has a suite of
classes for managing this storage, including classes for adding, deleting, and
moving messages.

✦ Transportation— javax.mail.Transport is the class responsible for the delivery


of messages. In the majority of instances, SMTP protocol is used for delivery.

The Transport class offers the following static method for sending messages

Transport.send( msg );

The send(...) methods throw a SendFailedException with a whole host of


diagnostic information that gives a clue as to which addresses got a successful
delivery notification.

3.9 JavaMail API

3.9.1 Sending e-mail and attachments


Probably the first thing to do is send some e-mail. It is already demonstrated
how to send a basic plain-text e-mail using the SMTP protocol, but have a look
at an application that is a little more functional.

The class javamail_send, takes the four following parameters:

✦ SMTP host
✦ to e-mail
✦ from e-mail
✦ e-mail body

The e-mail message is created in the usual way with the MimeMessage class, using
as little information as possible. After all the necessary properties of the message
are set, the static method Transport.send(...)is used to the deliver the message.

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

3.9.2 Receiving e-mail


Receiving e-mail is as simple as sending e-mail. The majority of the concepts of
dealing with mail by building a simple command-line access tool to POP3 mail.
This will be a very simple tool, and it most certainly will not replace Outlook or
Eudora client!

3.9.3 Deleting mail


The POP client can be extended to include the ability to delete a message in the
folder. It can simply added to the message loop the ability to handle the delete
<id> command, which deletion in turn calls the deleteSingleMethod(...) shown next.

This method parses out the message id and retrieves that message. We wish to
delete this message, and as we know from the previous sections, no explicit
delete method exists for the message.

3.9.4 Receiving attachments


The final piece of functionality is ought to add is the ability to save attachments to
disk. Add the save <id> command, which will look up a given message, see if any
attachments are associated with it, and then save it into the current directory.

The saving out is a simple matter of reading a byte from the InputStream of the
part object and writing it out to an appropriate FileWriter class.

3.10 Integrating JavaMail into J2EE


The mail Session object is used to communicate with transport layer to send e-
mail would have the hostname/ip address and might even include some
authentication to gain the right to relay e-mail.

J2EE enables to declare a resource at runtime under the comp/env/mail JNDI


context name, to which can attach the properties for SMTP. Many of the J2EE
application servers will provide access to this information through their own
administration tools. Failing that, look at the application server’s own
documentation for declaring JavaMail resource contexts.

Instead of creating the Properties object as before, the Session object using
JNDI with the context name of mail/mySMTP can be used.

public void sendE-mail()


{
try
{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup(“java:comp/env”);
Session session = (Session) envCtx.lookup(“mail/mySMTP”);
Message msg = new MimeMessage( session );

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

//--[ Set the FROM, TO, DATE and SUBJECT fields


msg.setFrom( new InternetAddress( “[email protected]” ) );
msg.setRecipients( Message.RecipientType.TO,
InternetAddress.parse(“[email protected]”) );
msg.setSentDate( new Date() );
msg.setSubject( “Hello World!” );
//--[ Create the body of the mail
msg.setText( “Hello from my first e-mail sent with JavaMail” );
//--[ Ask the Transport class to send our mail message
Transport.send( msg );
}
catch(Exception E)
{
System.out.println( “Oops something has gone pear shaped!”);
System.out.println( E );
}
}

This allows the component to remain completely generic and enables the
administrator to decide which mail devices he or she wishes to connect to. In
this respect, the JavaMail API is very much like the JDBC driver.

3.11 Understanding Java Messaging Services


The key concepts that surround messaging— the different messaging models,
point-to-point and publish-subscribe, message-oriented middleware, and the
various classes implemented in any application that uses messaging.

3.11.1 Explaining Messaging


The basic concept behind messaging is that distributed applications can
communicate using a self-contained package of business data and routing headers.
These packages are messages.

In contrast to Remote Method Invocation (RMI) or Hypertext Transfer Protocol


(HTTP), with which a client contacts a server directly and conducts a two-way
conversation, messaging-based apps communicate asynchronously through a
messaging server. That is, when a message is sent to another application the
sender does not wait for a response.

The software services that support message-based applications are referred to as


message-oriented middleware. Messaging is typically used in situations like
enterprise-application integration (EAI) and business-to-business (B2B)
communications.

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

3.11.2 Introducing JMS


JMS is the Java Messaging Service. It is a wrapper API that does not provide any
services directly, but instead serves to standardize the messaging functionality
provided by some other service provider, like IBM’s MQSeries (now WebSphere
MQ) or Sonic Software’s SonicMQ.

JMS provides a single API that can be used to access the messaging facilities
provided by any messaging-service provider, much as Java Database Connectivity
(JDBC) is used to access any relational database that provides a JDBC driver.

Message structure
The first element of JMS to understand is how messages are structured. A
message consists of the three following parts:

✦ Headers
✦ Properties
✦ Body

The message headers provide a fixed set of metadata fields describing the message,
with information such as where the message is going and when it was received.

The properties are a set of key-value pairs used for application-specific purposes,
usually to help filter messages quickly when they’ve been received.

The body contains whatever data is being sent in the message. The contents of
the body vary depending on the type of the message: The javax.jms.Message
interface has several sub interfaces for different types of messages.

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

3.11.3 Messaging Models


JMS supports two different messaging models: point-to-point (p2p) and publish-
and-subscribe (pub/sub).

Point-to-point messaging
In the point-to-point model messages are sent from producers to consumers via
queues. A given queue may have multiple receivers but only one receiver may
consume each message.

Publish-and-subscribe messaging
In the publish-and-subscribe messaging model, messages are sent (published)
to consumers via topics. Messages published on a specific topic are sent to all
message consumers that have registered (subscribed) to receive messages on
that topic.

3.11.4 Major JMS Components


This section discusses the following components:

✦ Destinations
✦ Connections
✦ Connection factories
✦ Sessions
✦ Producers
✦ Consumers

(i) Destinations
A destination is, as its name implies, somewhere you’re sending a message.
Specific types of destinations are queues (in point-to-point systems) or topics (in
publish/subscribe systems).

(ii) Connections
JMS Connections are similar to the Connection class in JDBC—it represents a
connection between the application and the messaging server over which
messages can be sent.

(iii) Connection factories


As in JDBC, connections in JMS are not directly instantiated. Instead, a
connection factory creates connections. Connection factories and destinations
are the only types of objects in JMS that need to be obtained via JNDI.

(iv) Sessions
Messages cannot send and receive messages directly through a connection.
Instead, a Session is needed. A session serves as a factory for message objects,
message producers and consumers, TemporaryTopics, and TemporaryQueues. It
also does the following:

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

 Provides transactional behavior for the work done by its producers


and consumers
 Defines a serial order for the messages it consumes and the
messages it produces
 Retains messages it consumes until they have been acknowledged.

Sessions are created using a Connection object. The session interface is javax.
jms.Session.

(v) Producers
A message producer is an object created by a session and is used for sending
messages to a destination. The Point To Point form of a message producer
implements the QueueSender interface. The pub/sub form implements the
TopicPublisher interface.

(vi) Consumers
A message consumer is an object created by a session and is used for receiving
messages sent to a destination. A message consumer allows a JMS client to
register interest in a destination with a JMS provider. The JMS provider manages
the delivery of messages from a destination to the registered consumers of the
destination. The PTP form of message consumer implements the QueueReceiver
interface. The pub/sub form implements the TopicSubscriber interface.

3.11.5 Reliable Messaging


JMS has a number of features that help ensure reliability.

Autonomous messages
First of all messages are autonomous—they are generated by a producer,
received by a consumer, and may then be retransmitted to another consumer.
Persistent messages
Messages marked as persistent are guaranteed to be delivered by the messaging
server. Once a message is successfully received it will be stored in a persistent
data store like a database or a file until it can be delivered to a consumer.

Synchronous acknowledgments
Finally, a variety of synchronous acknowledgements exist in the otherwise
asynchronous message-transmission process. When a JMS client attempts to
send a message, it first goes to the JMS server, which acknowledges successful
receipt of the message.

3.12 Transactions

When atomic delivery of several messages is needed—that is, either all the
messages are delivered or none is—a transaction is needed. JMS supports

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.


JEE_UNIT_III_JSP_E_CONTENT

transactions in two ways—via the JMS transaction support in the Session


interface and via the distributed-transaction support in the Java Transaction API.

To create a session with transactional behavior, simply specify true as the first
parameter passed to createSession(). The new session object is now transacted.

All messages sent through any producer created using that session are part of
the transaction until either rollback() or commit() is invoked on the session.
Once a transaction is completed by either a commit or rollback a new transaction
is started automatically.

The following code fragment shows how a set of messages can be handled inside
a transaction.

Session session =
connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(Destination);
// send some messages via producer
if(successful)
session.commit();
else
session.rollback();

Transactions are a very powerful tool and a necessity in any environment where
data integrity is the primary concern.

Prepared by H.Riaz Ahamed, Assistant Professor, The New College,Chennai-14.

You might also like