JEE E Content Unit III JSP23
JEE E Content Unit III JSP23
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.
3.1 Introduction
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().
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.
✦ 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%>
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.
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.
• 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.
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:
• Beans—Bean actions allow creation and use of JavaBeans inside a JSP. The
bean actions are explained in the Forms, JavaBeans, and JSP topic.
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:
The flush attribute tells the servlet engine to flush the output buffer before
including the file.
✦ out—This variable represents the JspWriter class, which has the same
functionality as the PrintWriter class in servlets.
Example: <% out.println(“Enter flight destination”); %>
✦ page—This variable represents the instance of the JSP’s Java class processing
the current request.
(i) Page Scope: Objects with page scope are accessible only within the page in
which they are created.
(ii) Request scope: Objects with request scope are accessible from pages
processing the same request in which they are created.
(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.
(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.
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.
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);
%>
isErrorPage attribute
The isErrorPage attribute indicates whether or not the current page can act as the
error page for another JSP page.
error.jsp
<form action="index.jsp">
<%@page isErrorPage="true"%>
Sorry, an Exception has occured!
Exception is <%=exception %>
<input type="submit" value="Re-Compute">
</form>
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.
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)
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.
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.
3.7 JavaMail
The JavaMail is an API that is used to compose, write and read electronic
messages (emails).
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.
The Message class implements the javax.mail.Part interface, which deals with
the functionality associated with constructing the header and the content.
The Transport class offers the following static method for sending messages
Transport.send( msg );
✦ 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.
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.
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.
Instead of creating the Properties object as before, the Session object using
JNDI with the context name of mail/mySMTP can be used.
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.
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.
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.
✦ 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.
(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:
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.
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
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.