EJ Unit 4
EJ Unit 4
Java
Vidyalankar School of
Information Technology
Wadala (E), Mumbai
www.vsit.edu.in
Beena Kapadia
1
Compiled by: Beena Kapadia
Introduction to Enterprise Java Beans: Enterprise Bean Architecture, Benefits of Enterprise Bean,
Types of Enterprise Bean, Accessing Enterprise Beans, Enterprise Bean Application, Packaging
Enterprise Beans
Working with Session Beans: When to use Session Beans? Types of Session Beans, Remote and Local
Interfaces, Accessing Interfaces, Life cycle of Enterprise Beans, Packaging Enterprise Beans, Example
of Stateful Session Bean, Example of Stateless Session Bean, Example of Singleton Session Beans.
Working with Message Driven Beans: Life cycle of a Message Driven Bean, Uses of Message Driven
Beans, The Message Driven Beans Example.
Interceptors: Request and Interceptor, defining an Interceptor, AroundInvoke Method, Applying
Interceptor, Adding an Interceptor To An Enterprise Bean, Build and Run the Web Application.
Java Naming and Directory Interface: What is Naming Service? What is Directory Service? What is
Java Naming and Directory interface? Basic Lookup, JNDI Namespace in Java EE, Resources and JNDI,
Datasource Resource Definition in Java EE.
Recommended Books :
Java EE 7 For Beginners by Sharanam Shah, Vaishali Shah
Java EE 8 Cookbook: Build reliable applications with the most robust and mature technology for
enterprise development by Elder Moraes
Advanced Java Programming by Uttam Kumar Roy
2
Compiled by: Beena Kapadia
Unit IV Enterprise Java Beans
Enterprise beans are Java EE components that implement Enterprise JavaBeans (EJB)
technology. Enterprise beans run in the EJB container, a runtime environment within
GlassFish Server. Although transparent to the application developer, the EJB container
provides system-level services, such as transactions and security, to its enterprise beans.
These services enable you to quickly build and deploy enterprise beans, which form the core
of transactional Java EE applications.
• Enterprise application systems broken into layers and each layer made up of one or more
logical components
• This approach helps the developers in:
– Managing the complexity of software projects in easier way
– Having great discipline to software development process
– Cutting the development time drastically
Enterprise Java Bean Architecture
• It defines a model for the development and deployment of reusable java server components
• component architecture is the backbone of the java EE platform
• EJB architecture is composed of:
• AN Enterprise Bean Server
• Enterprise Bean Container that runs within the server
• Enterprise Bean that runs within this container
• Enterprise Bean Client
• Java Naming & Directory Interface [JNDI] and Java Transaction Services [JTS]
Request and Response
EJB Client
• EJB client finds Enterprise Beans through a JNDI (Java Naming and Directory
Interface). The client then requests for EJB methods via EJB container
• An EJB client could be remote or local
• A remote client runs on a different machine & a different JVM than the enterprise
bean it accesses. The location of the enterprise bean is transparent to a remote client.
• A local client runs in the same JVM as the enterprise bean it accesses.
4
Compiled by: Beena Kapadia
The EJB model allows developer to concentrate on Business logic, while web
page designer concentrate on formatting output
– Distributed deployment: the enterprise beans are deployed across multiple
servers on a network and client can access any of these enterprise beans
methods either remotely or locally
– Application Interoperability between Java and non-Java applications:
Enterprise architecture is mapped to industrial standard. Hence it is relatively
simple to craft an EJB and make it work with components developed in a
different languages like VC++ and so on.
Types of Enterprise Beans
1. Session Beans
– A session bean object is a short-lived object that executes on behalf of a
single client that runs on the application server.
– A session bean is non persistence enterprise bean that encapsulates business
logic onto which a client can take action (accessing data / updating data)
across Local or Remote client view.
– Mapping of client and session is one-to-one
Types of Session Beans
Stateless Session Bean:
• Stateless beans simply do not remember anything about the client between the calls
of the method.
• Because, they are stateless, these bean types are lightweight & provide a high degree
of scalability.
• A stateless session bean can implement a web service, but other types of enterprise
beans cannot.
• E.g. swiping of credit / debit card
Stateful Session bean
• Stateful session bean maintains a client specific session information of a single
client across multiple method calls and transactions.
• It exists for the duration of a single client / server session. Only a single client can use
a stateful session bean at a time.
• The container typically maintains a Stateful session beans object state in main
memory, even across transactions, although the container may swap that to
secondary storage when deactivating the session bean.
• Only a single client can use a Stateful session bean at a time.
• The state is retained for the duration of the client bean session. If the client removes
the bean or terminates, the session ends & the state disappears.
• Example: Shopping Cart
In other words:
• Stateful Session Beans are business objects having state (values of its instance
variables)
• Because the client interacts (“talks”) with its bean, this state is often called the
conversational state and represents a unique client-bean session.
• The @Stateful annotation is used to mark the class as Stateful Session Bean.
• In Stateful client, a client’s call creates an instance of Session Bean to serve only that
client.
• A session bean is not shared (pooled) i.e. Access to the bean instance is strictly
limited to only one client at a time.
• A business process can have multiple methods or transactions.
5
Compiled by: Beena Kapadia
• When the client terminates, its session bean appears to terminate and is no longer
associated with the client.
• When the client invokes a method on the bean marked with @Remove, it signals the
end of the session with the bean.
• The state is retained for the duration of the client-bean session. If the client removes
the bean, the session ends and the state disappears.
Singleton session bean
• Singleton session bean are instantiated once per application & exist for the lifecycle
of the application.
• These kinds of session beans are useful where a single enterprise bean instance is
shared across applications and are concurrently accessed by clients.
• Singleton session bean offer similar functionality to stateless session bean but differ
from stateless session bean as:
– There is only one singleton session bean per application
– There are pool of stateless beans, any of which may respond to a client
request.
2. Message Driven beans
• Message driven beans are enterprise beans that receives and process Java
Messaging Services (JMS) messages
• Unlike session and entity beans, message driven beans have no interfaces
• They do not maintain any conversational state
• They allow asynchronous communication between the listener and the queue
• The messages may be sent by any component, an application client, another
enterprise bean or a web component
• They do not have business methods but define a message listener method, which the
EJB container invokes to deliver messages.
• They are relatively short lived
Accessing Enterprise Beans
• Clients access enterprise beans either through
– A dependency injection() or
– through a business interface.
• A dependency injection, using Java programming language annotations of an
enterprise bean, which exposes the public methods of the enterprise bean
implementation class to clients. Clients using the no-interface view of an enterprise
bean may invoke any public methods in the enterprise bean implementation class or
any super classes of the implementation class.
• A business interface is a standard Java programming language interface that contains
the business methods of the enterprise bean.
6
Compiled by: Beena Kapadia
Source: https://www.youtube.com/watch?v=-gDBZmhD2q4
Using Enterprise Beans in Clients
The client of an enterprise bean obtains a reference to an instance of an enterprise bean
through either dependency injection (A Java class has a dependency on another class, if it
uses an instance of that class. We call this a class dependency), using Java programming
language annotations (@Inject), or JNDI lookup, using the Java Naming and Directory
Interface syntax to find the enterprise bean instance.
• Java EE application clients support dependency injection using the javax.ejb.EJB
annotation.
• Applications that run outside a Java EE server-managed environment, such as Java SE
applications, must perform an explicit lookup. JNDI supports a global syntax for
identifying Java EE components to simplify this explicit lookup.
The Contents of an Enterprise Bean or Enterprise Bean Application
To develop an enterprise bean, you must provide the following files.
• Enterprise bean class: Implements the business methods of the enterprise bean and
any lifecycle callback methods.
• Business interfaces: Define the business methods implemented by the enterprise bean
class. A business interface is not required if the enterprise bean exposes a local, no-
interface view.
• Helper classes: Other classes needed by the enterprise bean class, such as exception
and utility classes.
Naming Conventions for Enterprise Beans
• Because enterprise beans are composed of multiple parts, it is useful to follow a
naming convention for your applications. Following table summarizes the
conventions for the example beans in this tutorial.
Item Syntax Example
Enterprise bean name nameBean AccountBean
Enterprise bean class nameBean AccountBean
Business interface Name Account
7
Compiled by: Beena Kapadia
Structure of EJB JAR
Packaging Enterprise Beans in WAR Modules
• Enterprise beans often provide the business logic of a web application. In these cases,
packaging the enterprise bean within the web application's WAR module simplifies
deployment and application organization.
• To include enterprise bean class files in a WAR module, the class files should be in
the WEB-INF/classes directory.
• To include a JAR file that contains enterprise beans in a WAR module, add the JAR
to the WEB-INF/lib directory of the WAR module.
• WAR modules that contain enterprise beans do not require an ejb-jar.xml deployment
descriptor. If the application uses ejb-jar.xml, it must be located in the WAR module's
WEB-INF directory.
• For example, suppose that a web application consists of a shopping cart enterprise
bean, a credit card–processing enterprise bean, and a Java servlet front end. The
shopping cart bean exposes a local, no-interface view and is defined as follows:
• package com.example.cart;
• @Stateless
• public class CartBean { ... }
• The credit card–processing bean is packaged within its own JAR file, cc.jar, exposes a
local, no-interface view, and is defined as follows:
• package com.example.cc;
• @Stateless
• public class CreditCardBean { ... }
• The servlet, com.example.web.StoreServlet, handles the web front end and uses both
CartBean and CreditCardBean. The WAR module layout for this application is as
follows:
• WEB-INF/classes/com/example/cart/CartBean.class
• WEB-INF/classes/com/example/web/StoreServlet
• WEB-INF/lib/cc.jar
• WEB-INF/ejb-jar.xml
• WEB-INF/web.xml
Some examples
Example: shopping cart
Step 1 creating application
File -> new project-> java web->web application -> Prac6CShoppingCartApp -> select
Use dedicated folder for storing libraries -> finish
Step 2: Creating a stateful session bean
8
Compiled by: Beena Kapadia
Source package -> new -> other -> enterprise java beans -> session bean -> next -> new
session bean -> ejb name: ->ShoppingCart -> package: -> ejb -> session type option ->
Stateful -> finish.
ShoppingCart.java
package ejb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
@Stateful
public class ShoppingCart {
List<String> contents;
String customerName;
9
Compiled by: Beena Kapadia
public void removeBook(String title) {
try {
stmt = conn.createStatement();
query = "DELETE FROM cart WHERE UserName='" + customerName + "' AND
ItemName='" + title + "'";
stmt.executeUpdate(query);
} catch(SQLException e) {
System.err.println("Sorry failed to delete values from the database table. " +
e.getMessage());
} }
public List<String> getContents() {
try {
stmt = conn.createStatement();
query = "SELECT * FROM cart WHERE UserName='" + customerName + "'";
rs = stmt.executeQuery(query);
while(rs.next()) {
contents.add(rs.getString("ItemName"));
}
} catch(SQLException e) {
System.err.println("Sorry failed to select values from the database table. " +
e.getMessage());
}
return contents;
}
@Remove()
public void remove() {
contents = null;
}
}
Step 3: creating a web client using index.jsp
Right click on wewb pages -> new -> JSP -> filename -> index -> finish.
10
Compiled by: Beena Kapadia
cart.initialize(request.getParameter("txtCustomerName"));
} else {
cart.initialize("Guest");
}
if (request.getParameter("btnRmvBook") != null) {
String books[] = request.getParameterValues("chkBook");
if (books != null) {
for (int i=0; i<books.length; i++) {
cart.removeBook(books[i]);
}
}
}
if (request.getParameter("btnAddBook") != null) {
String books[] = request.getParameterValues("chkBook");
if (books != null) {
for (int i=0; i<books.length; i++)
{
cart.addBook(books[i]);
}
}
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Shopping Cart</title>
</head>
<body style="background-color: pink;">
<h1 style="text-align: center;">Books For Sale</h1><br>
<form method="post">
Customer Name: <input type="text" name="txtCustomerName" value=<%=
request.getParameter("txtCustomerName")%> /><br>
<b>Book Titles</b><br>
<input type="checkbox" name="chkBook" value="Struts 2.0 For
Beginners">Struts 2.0 For Beginners<br>
<input type="checkbox" name="chkBook" value="Oracle 11g For
Professionals">Oracle 11g For Professionals<br>
<input type="checkbox" name="chkBook" value="Hibernate 3 For
Beginners">Hibernate 3 For Beginners<br>
<input type="checkbox" name="chkBook" value="Java Persistence API In
EJB 3 For Beginners">Java Persistence API In EJB 3 For Beginners<br>
<br>
<input type='submit' value='Add To My Basket' name='btnAddBook'>
<input type='submit' value='Remove From My Basket'
name='btnRmvBook'><br><br><br>
<%
if(cart!=null)
{
out.print("<b>Basket</b><br>");
11
Compiled by: Beena Kapadia
List<String> bookList = cart.getContents();
Iterator iterator = bookList.iterator();
while (iterator.hasNext())
{
String title = (String) iterator.next();
%>
<%= title %><br>
<%
}
}
%>
</form>
</body>
</html>
Step 4:
Create database and database table
Services -> create database -> cartdb ->select cartdb - > right click -> create table ->
cart -> UserName varchar 35
ItemName varchar 50
Finish.
Step 5.
Add mysql connector to the library under project tab.
Step 6: build and run the application.
12
Compiled by: Beena Kapadia
}
CCBean.java
package mybeans;
import javax.ejb.Stateless;
@Stateless
public class CCBean implements CCBean1Local
{
public double r2Dollar(double r)
{
return r/65.65;
}
public double d2Rupees(double d)
{
return d*65.65;
}
}
Index.html
<html>
<head>
<title>Room Reservation</title>
</head>
<body>
13
Compiled by: Beena Kapadia
<form method="post" action="RoomClient">
<br> No of Rooms <input type=text name="t1">
<br> <input type="submit" name="btn" value="CheckIN">
<br> <input type="submit" name="btn" value="CheckOUT">
</form>
</body>
</html>
Step2: Create a session bean named as RoomBean in the package named ejb. Select
the option Stateless and click on Local Interface.
Here you will find two files created in the ejb package named as RoomBean.java and
RoomBeanLocal.java
RoomBeanLocal.java
package ejb;
import javax.ejb.Local;
@Local
public interface RoomBeanLocal {
public int checkin(int no);
public int checkout(int no);
}
RoomBean.java
package ejb;
import javax.ejb.Stateless;
import java.sql.*;
@Stateless
public class RoomBean implements RoomBeanLocal {
public int checkin(int no) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/roomdb","root","tiger");
String sql1 = "select * from room";
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql1);
rs.next();
int total=rs.getInt(1);
int occ=rs.getInt(2);
int free=total-occ;
System.out.println(total);
System.out.println(free);
if (free>=no)
{
String sql2="update room set occ=?";
PreparedStatement ps=con.prepareStatement(sql2);
ps.setInt(1, occ+no);
int res=ps.executeUpdate();
return res;
}
else return 0;
}
14
Compiled by: Beena Kapadia
catch(Exception e)
{
return 0;
}
}
public int checkout(int no) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/roomdb","root","tiger");
String sql1 = "select * from room";
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql1);
rs.next();
int total=rs.getInt(1);
int occ=rs.getInt(2);
if (occ>=no)
{
String sql2="update room set occ=?";
PreparedStatement ps=con.prepareStatement(sql2);
ps.setInt(1, occ-no);
int res=ps.executeUpdate();
return res;
}
else return 0;
}
catch(Exception e)
{
return 0;
}
}
}
Step 3: Create a Servlet file named as RoomClient. Do not click on web.xml
(Deployment Descriptor)
package servlet;
import ejb.RoomBeanLocal;
import java.io.*;
import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
15
Compiled by: Beena Kapadia
try {
int no=Integer.parseInt(request.getParameter("t1"));
String b=request.getParameter("btn");
int res=0;
if(b.equals("CheckIN"))
{
res=obj.checkin(no);
if (res==1)
out.println(no + " rooms check-in");
}
if(b.equals("CheckOUT"))
{
res=obj.checkout(no);
if (res==1)
out.println(no + " rooms check-out");
}
if(res==0)
out.println("Not possible to do Check IN / OUT");
out.println("<br><br><a href=index.html> Back </a>");
}
finally {
out.close();
}
}
}
Working with session beans
• A session bean encapsulates business logic that can be invoked programmatically by
a client over local, remote, or web service client views.
• To access an application that is deployed on the server, the client invokes the session
bean's methods.
• A session bean is not persistent.
It can be accessed from:
• Remote / Local java clients
• Web service clients
• Component running in the same server
A session Bean cannot:
• Be shared by more than one client at a time
• Be called by the same client using multiple threads
• Directly represent data in a database
They are relatively short-lived. That means they are removed as soon as client removes them
or when EJB container shuts down.
When to use Session Beans?
• At a given time, only one client has access to the bean instance
• The state of bean is not persistence, existing only for a short period of time
For example:
• Performing database operations such as creating a new record, modifying / deleting
existing records
• Managing the contents of a shopping cart
The Life Cycle of a Stateless Session Bean
16
Compiled by: Beena Kapadia
• Because a stateless session bean is never passivated, its life cycle has only two
stages: nonexistent and ready for the invocation of business methods. Following
Figure illustrates the stages of a stateless session bean.
• The client initiates the life cycle. The EJB container instantiates and maintains a
pool of beans and then performs any dependency injection and invokes the method
annotated @PostConstruct [if it exists]. The bean is now ready to have its business
methods invoked by a client.
• At the end of the life cycle, the client invokes a method annotated @PreDestroy [if
any]. The bean's instance is ready for garbage collection
The Life Cycle of a Stateful Session Bean
• Figure on the next slide illustrates the stages that a session bean passes through during
its lifetime. The client initiates the life cycle by obtaining a reference to a stateful
session Bean. The EJB container instantiates the bean by any dependency injection
and then invokes the method annotated with @PostConstruct [if any]. The bean is
now ready to have its business methods invoked by client.
• While in the ready stage, the EJB container may decide to deactivate, or passivate, the
bean by moving it from memory to secondary storage. The EJB container invokes the
bean's ejbPassivate method immediately before passivating it. If a client invokes a
business method on the bean while it is in the passive stage, the EJB container
activates the bean, calls the bean’s method annotated @PostActivate [if any], and then
moves it to the ready stage.
17
Compiled by: Beena Kapadia
•At the end of the life cycle, the client invokes a method annotated @PreDestroy [if
any]. The bean's instance is ready for garbage collection.
The Lifecycle of a Singleton Session Bean
• Like a stateless session bean, a singleton session bean is never passivated and has
only two stages, nonexistent and ready for the invocation of business methods, as
shown in the following Figure
The EJB container initiates the Singleton Bean life cycle by creating the singleton instance.
This occurs upon application deployment if the singleton is annotated with the @Startup
annotation. The container performs any dependency injection and then invokes the method
annotated @PostConstruct [if it exists]. The singleton bean is now ready to have its business
methods invoked by the client.
At the end of the life cycle, the EJB container calls method annotated @preDeploy [if it
exists]. The singleton session bean is now ready for garbage collection.
Web-> web application -> Pract7AServletHitsApp -> finish.
Step 1: Index.html
<html>
<head>
<title>Servlet Client</title>
<meta http-equiv="Refresh" content="0; URL=ServletClient">
</head>
<body>
</body>
</html>
Step2: Create a Session Bean named as CountServletHitsBean Select Singleton
package name as ejb
package ejb;
import javax.ejb.Singleton;
@Singleton
public class CountServletHitsBean {
18
Compiled by: Beena Kapadia
Step 3: Create a Servlet File name ServletClient in the package name as servlet. Do not
select the Deployment Descriptor file.
package servlet;
import java.io.*; import javax.ejb.EJB; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;import ejb.CountServletHitsBean;
@WebServlet(name = "ServletClient", urlPatterns = {"/ServletClient"})
public class ServletClient extends HttpServlet {
@EJB CountServletHitsBean obj;
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
PrintWriter out= resp.getWriter();
try {
out.println("<h1>Number of times this Servlet is accessed: "+obj.getCount()+"</h1>");
} catch (Exception e) {
}
}
}
The Life Cycle of a Message-Driven Bean
• Following Figure illustrates the stages in the life cycle of a message-driven bean.
• The EJB container usually creates a pool of message-driven bean instances. For each
instance, the EJB container instantiates the bean and performs these tasks:
– It calls the setMessageDrivenContext method to pass the context object to
the instance.
– It calls the instance's ejbCreate method.
• Like a stateless session bean, a message-driven bean is never passivated, and it has
only two states: nonexistent and ready to receive messages.
• At the end of the life cycle, the container calls the ejbRemove method. The bean's
instance is then ready for garbage collection.
• A message driven bean is a stateless, server-side, transaction-aware component that is
driven by a Java message (javax.jms.message).
• A message-driven bean is an enterprise bean that allows Java EE applications to
process messages asynchronously.
19
Compiled by: Beena Kapadia
• This type of bean normally acts as a JMS message listener, which is similar to an
event listener but receives JMS messages instead of events. The messages can be sent
by any application client or a web client.
• Message-driven beans can process JMS messages or other kinds of messages.
• When a message arrives, the container calls the message-driven bean’s onMessage
method to process the message. The onMessage method normally casts the message
to one of the five JMS message types and handles it in accordance with the
application’s business logic. The onMessage method can call helper methods or can
invoke a session bean to process the information in the message or to store it in a
database.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
20
Compiled by: Beena Kapadia
<body>
Welcome to My Home Page
<%
try{
InitialContext ic= new InitialContext();
queue= (Queue)ic.lookup("jms/Queue");
connectionFactory=(ConnectionFactory)ic.lookup("jms/QueueFactory");
connection= connectionFactory.createConnection();
mySession=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
messageProducer=mySession.createProducer(queue);
message=mySession.createTextMessage();
message.setText(request.getRemoteAddr());
messageProducer.send(message);
}
catch(JMSException e)
{
System.out.println("Exception Occoured "+e.toString());
}
%>
</body>
</html>
Step2: Create a Database name visitorstat Create table name userstat
column names
Firstvisitdt – timestamp
Hostname – varchar 30 Primary Key
Visits – int
Step3: Create a Session Bean named as VisitorStatBean Select Stateless
package name as ejb, do not select Local / Remote
package ejb;
import java.sql.*;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
@Stateless
public class VisitorStatBean {
@PostConstruct
public void connect()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection("jdbc:mysql://localhost/visitorstat", "root",
"tiger");
}
21
Compiled by: Beena Kapadia
catch (Exception e) {
System.err.println(e.getMessage());
}
}
@PreDestroy
public void disconnect()
{
try {
conn.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public void addVisitor(String host)
{
try {
st= conn.createStatement();
query="insert into userstat (hostname,visits) values ('"+host+"','1')";
st.executeUpdate(query);
}
catch (SQLException e)
{
try {
st=conn.createStatement();
query="update userstat set visits=visits+1 where hostname='"+host+"' ";
st.executeUpdate(query);
}
catch (SQLException ex) {
System.err.println("Cannot Update"+e.getMessage());
}
}
}}
Step 4: Right click on Source Packages Select New Other Enterprise Java
Bean MessageDrivenBean EJB Name: BasicMessageBean Package: ejb
Select Project Destination Click on Add Button Destination Name:
jms/Queue Destination Type select the option Queue click on OK Click
on Next Activation Configuration Properties should be as it is. Click on Finish.
package ejb;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
22
Compiled by: Beena Kapadia
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationLookup", propertyValue =
"jms/Queue"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue =
"javax.jms.Queue")
})
public class BasicMessageBean implements MessageListener {
@EJB VisitorStatBean vs;
@Resource
private MessageDrivenContext mdc;
public BasicMessageBean() {
}
@Override
public void onMessage(Message message) {
try {
if(message instanceof TextMessage){
TextMessage msg= (TextMessage) message;
vs.addVisitor(msg.getText());
}}
catch (JMSException e) {
mdc.setRollbackOnly();
}
}
}
Step 5:
Before deploying and running the application, Glassfish Server setting is required.
Browse the path:
Localhost:4848 on any browser.
Find Resources -> connectors -> Connector Resources double click on Connector
Resources -> click on ‘New’ Button -> write JNDI name as -> jms/QueryFactory.
Find Admin Object Resources and double click on that -> click on ‘New’ Button -> write
JNDI name as -> jms/Queue.
Now run index.jsp file.
Accessing Beans:
Remote interface:
If the client is not located in same application server as the bean instance, then use remote
interface to access the bean
Call to the remote interface requires marshalling arguments, transportation of the
marshalled data over the network, unmarshalling the arguments and dispatch at the
receiving end.
Remote EJB extends remote interface so that client communicates with EJB through
RMI/RMI IIOP which involves marshalling / unmarshalling for every method call.
Accessing Remote Interface
Client can access No-interface view either of the following two ways:
• Dependency injection
(@EJB Beanclassname objname)
• JNDI lookup
23
Compiled by: Beena Kapadia
(BeanClassname objname=(BeanClassname)InitialContext.lookup("java:global/
BeanClassname");
Local interface
The local EJB does not use RMI/RMI IIOP for communication
The bean must run in the same JVM while using local interface
Accessing Local Interface
Client can access Local Interface either of the following two ways:
• Dependency injection
(@EJB Beanclassname objname)
• JNDI lookup
(BeanClassname objname=(BeanClassname)InitialContext.lookup("java:module/
BeanClassname");
24
Compiled by: Beena Kapadia
(@EJB Beanclassname objname)
• JNDI lookup
(BeanClassname objname=(BeanClassname)InitialContext.lookup("java:module/
BeanClassname");
Method of accessing the enterprise Bean
Remote Clients
A remote client of an enterprise bean has the following traits (characteristics):
• It can run on a different machine and a different Java virtual machine than the
enterprise bean it accesses.
• It can be a web component, an application client, or another enterprise bean.
• To a remote client, the location of the enterprise bean is transparent.
• To create an enterprise bean that has remote access, you must code a remote
interface and a home interface. The remote interface defines the business methods
that are specific to the bean.
• The home interface defines the bean's life-cycle methods
Local Clients
A local client has these characteristics:
• It must run in the same JVM as the enterprise bean it accesses.
• It can be a web component or another enterprise bean.
• To the local client, the location of the enterprise bean it accesses is not transparent.
• To build an enterprise bean that allows local access, you must code the local
interface and the local home interface.
• The local interface defines the bean's business methods, and the local home interface
defines its life-cycle.
Step 1:
Create web application as pract7CMarksApp.
Step 2:
Create database marksdb
Step 3:
Create tables marks in marksdb database as:
create table marks (id int primary key auto_increment, sname varchar(35), marks1 int,
marks2 int, marks3 int);
step 4:
index.jsp
<%--
25
Compiled by: Beena Kapadia
Document : index
Created on : Sep 16, 2018, 6:26:05 PM
Author : Beena Kapadia
--%>
<%@page import="ejb.MarksEntryBean"%>
<%@page import="javax.naming.InitialContext"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
private static MarksEntryBean obj;
public void jspInit()
{
try
{
InitialContext ic=new InitialContext();
obj=(MarksEntryBean)ic.lookup("java:global/Pract7CMarksApp/MarksEntryBean");
}
catch(Exception e)
{
System.out.println(e);
}
}
%>
<%
if(request.getParameter("InsertMarks")!=null)
{
String sname;
int marks1, marks2, marks3;
sname = request.getParameter("sname");
marks1=Integer.parseInt(request.getParameter("m1"));
marks2=Integer.parseInt(request.getParameter("m2"));
marks3=Integer.parseInt(request.getParameter("m3"));
obj.addMarks(sname,marks1,marks2,marks3);
out.print("Marks entered successfully..!!!!");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>Enter Details</h2>
<form name="result" method="post">
Enter student's name: <input type='text' name="sname" /><br>
Enter subject 1 marks: <input type='text' name="m1" /><br>
Enter subject 2 marks: <input type='text' name="m2" /><br>
26
Compiled by: Beena Kapadia
Enter subject 3 marks: <input type='text' name="m3" /><br>
<input type='submit' name="InsertMarks" /><br>
</form>
</body>
</html>
Step 4:
create stateful java bean as
select source package -> session bean -> class name -> MarksEntryBean -> package -> ejb ->
bean type-> stateful -> don’t select Local / Remote -> finish.
package ejb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.ejb.Stateful;
@Stateful
public class MarksEntryBean {
String sname;
int m1,m2,m3;
Connection con=null;
Statement st=null;
String query="";
public void addMarks(String sname,int m1,int m2,int m3)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/marksdb",
"root","tiger");
st=con.createStatement();
query="insert into marks (sname,marks1,marks2,marks3) values
('"+sname+"','"+m1+"','"+m2+"','"+m3+"')";
st.executeUpdate(query);
System.out.print("Marks entered sucessfully!!");
}
catch(Exception e){System.out.println(e);}
}}
27
Compiled by: Beena Kapadia
Source: https://www.youtube.com/watch?v=k3dhvcETsyY
EJB Message Driven Bean JMS Theory
28
Compiled by: Beena Kapadia
e.printStackTrace();
mdc.setRollbackOnly();
} catch (Throwable te) {
te.printStackTrace();
}
}
Uses of Message Driven Beans
Message driven beans are used
To asynchronous communication between enterprise bean components
To have message automatically delivered
To increment two applications in a loosely coupled but in reliable manner
To create message selectors. A message selector is designed to take on only specific
messages, thus making it possible to use Message Driven Beans as triggers
Introduction to interceptors
An interceptor is a method that you can interpose in the invocation flow of an enterprise
bean. You can define an interceptor to intercept an enterprise bean's business methods: the
interceptor method will be executed before any of the bean's business methods are invoked.
The interceptors can also be defined as an object that is invoked at the pre-processing and
post-processing of a request, which can be used to perform operations such as validation,
exception handling, internationalization, displaying intermediate results etc.
Request and interceptor
Every request that is received passes through each Interceptor. The interceptor can:
Ignore the request
Act on request data
Break the request and prevent the EJB class method from firing
Since interceptors deal with EJB, they have access to the EJB class being executed as well as
all environmental variables and execution properties.
Defining an interceptor
Interceptors can be defined in Java as a method interceptor or a class interceptor. The
preferred way to define in Java code is by using meta-data annotations. They can be defined
in the application descriptor as well, but, in that case they are not portable across Java EE
servers. Some of the meta-data annotations found in the javax.interceptor package
are: @AroundInvoke, @AroundTimeout, @PostConstruct, and @PreDestroy.
An AroundInvoke method can be defined by either of the following methods:
Annotating the method with an @AroundInvoke annotation [ recommended ]
Using an element in the bean’s deployment descriptor
An AroundInvoke method must satisfy the following requirements:
One AroundInvoke method is allowed for each class
It must have a no argument public constructor
It must accept an javax.interceptor.InvocationContext object as an argument and
return a java.lang.Object object
It can throw any application exception that is specified in the business interface or any
runtime exception
It can be declared private, package private, protected or public
It must call InvocationContext.proceed() to signal its intention to continue the
invocation
Applying Interceptors to Visitor Statistics Application
29
Compiled by: Beena Kapadia
Let’s create an interceptor that prints the time it takes to run the intercepted business method
of the VisitorState class of the visitor statistics example.
Create a Java class [interceptor] called EJBMethodTimer.
To create a Java class, right click Source package -> new -> Java Class.
Enter EJBMethodTimer in the class name text box and enter interceptor in the package
textbox.
Click finiish
Enter following code in EJBMethodTimer.
package interceptor;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
public class EJBMethodTimer
{
public EJBMethodTimer ()
{}
@AroundInvoke
private Object intercept (InvocationContext ic) throws Exception
{
long t1=System.nanoTime();
Object result=ic.proceed(); // invokes beans method
long t2=System.nanoTime();
System.out.println("="+ic.getMethod().getName()+"("+ic.getParameters()[0]+")took:
"+((t2-t1)/1000.0)+" nano seconds.");
return result;
}
}
Adding interceptors to An Enterprise Bean
The lines in bold are the changes made to the original program
package ejb;
import interceptor.EJBMethodTimer;
import javax.interceptor.Interceptors;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
@Stateless
@Interceptors({EJBMethodTimer.class})
public class VisitorStat {
private Connection conn = null;
private ResultSet rs;
private Statement stmt = null;
private String query = null;
30
Compiled by: Beena Kapadia
@PostConstruct
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/visitorstatdb",
"root", "tiger");
System.out.println("Database connection established successfully.");
} catch(Exception e) {
System.err.println("Sorry failed to connect to the Database.");
}
}
@PreDestroy
public void disconnect() {
try {
conn.close();
System.out.println("Database connection closed successfully.");
} catch(SQLException e) {
System.err.println("Cannot close the database connection: " + e.getMessage());
}
}
Output:
31
Compiled by: Beena Kapadia
Source https://www.youtube.com/watch?v=NkWK_DGrNR8
java naming and directory interface
Java Naming and Directory Interface
The Java Naming and Directory Interface (JNDI) is an application programming interface
(API) that provides naming and directory functionality to applications written using the Jav
programming language.
What is Naming Service?
Naming Concepts
A fundamental facility in any computing system is the naming service. When using almost
any computer program or system, you are always naming one object or another. For example,
when you use an electronic mail system, you must provide the name of the recipient. To
access a file in the computer, you must supply its name. A naming service allows you to look
up an object given its name.
A naming service's primary function is to map people friendly names to objects, such as
addresses, identifiers, or objects typically used by computer programs.
For example, the Internet Domain Name System (DNS) maps machine names to IP
Addresses:
www.example.com ==> 192.0.2.5 (naming an object on the Internet)
32
Compiled by: Beena Kapadia
A file system maps a filename to a file reference that a program can use to access the contents
of the file.
c:\bin\autoexec.bat ==> File Reference (naming a file on the local file system)
These two examples also illustrate the wide range of scale at which naming services exist--
from naming an object on the Internet to naming a file on the local file system.
To look up an object in a naming system, you supply it the name of the object. The naming
system determines the syntax that the name must follow. This syntax is sometimes called the
naming systems naming convention. A name is made up components. A name's
representation consist of a component separator marking the components of the name.
Naming System Component Separator Names
UNIX file system "/" /usr/hello
DNS "." sales.Wiz.COM
The UNIX file system's naming convention is that a file is named from its path relative to the
root of the file system, with each component in the path separated from left to right using the
forward slash character ("/"). The UNIX pathname, /usr/hello, for example, names a
file hello in the file directory usr, which is located in the root of the file system.
DNS naming convention calls for components in the DNS name to be ordered from right to
left and delimited by the dot character ("."). Thus, the DNS name sales.Wiz.COM names a
DNS entry with the name sales, relative to the DNS entry Wiz.COM. The DNS
entry Wiz.COM, in turn, names an entry with the name Wiz in the COM entry.
A context is a set of name-to-object bindings. Every context has an associated naming
convention. A context always provides a lookup (resolution) operation that returns the object,
it typically also provides operations such as those for binding names, unbinding names, and
listing bound names. A name in one context object can be bound to another context object
(called a subcontext) that has the same naming convention.
33
Compiled by: Beena Kapadia
Each name must be expressed using syntax that is understood by Naming system.
Each naming context provides a set of names to the object binding; where object is the
system resource. Information about a particular object is stored as attributes of that object.
Information with the object is secured and can be accessed only by the authorised client.
A directory service defines a name space for a network.
A namespace is used to indicate a place that holds one or more objects as named entry.
A directory service behaves quite like a database. it provides advanced search possibilities
bound to multiple objects attributes exists within the directory.
Basic Lookup
To look up a resource, first you instantiate an InitialContext, then you use
the InitialContext.lookup() method to look up the resource by its JNDI name. The following
example catches NameNotFoundException and NamingException exceptions that can occur
during a lookup:
try {
InitialContext ic = new InitialContext();
String snName = "java:comp/env/mail/MyMailSession";
Session session = (javax.mail.Session)ic.lookup(snName);
}
catch (NameNotFoundException e) {
out("\nJNDI binding was not found");
}
catch (NamingException e) {
out("\nJNDI binding error");
}
JNDI Nam espace in Java EE 7
Three JNDI namespaces are used for portable JNDI lookups: java:global, java:module,
and java:app.
The java:global JNDI namespace is the portable way of finding remote enterprise beans
using JNDI lookups. JNDI addresses are of the following form:
34
Compiled by: Beena Kapadia
The module name is optional. The interface name is required only if the enterprise bean
implements more than one business interface.
For example, if an enterprise bean, MyBean, is packaged within the web application
archive myApp.war, the module name is myApp. The portable JNDI name
is java:module/MyBean An equivalent JNDI name using the java:global namespace
is java:global/myApp/MyBean.
35
Compiled by: Beena Kapadia
java:app—Names in this namespace are shared by all components and modules in an
application, for example, the application-client, web, and EJB components in an .ear
file.
java:global—Names in this namespace are shared by all the applications in the
server.
You can programmatically declare DataSource definitions using one of the following
methods:
Creating DataSource Resource Definitions Using Annotations
Creating DataSource Resource Definition Using Deployment Descriptors
Assignment Questions:
1. What is EJB? Explain its architecture.
2. What is EJB? Explain its advantages / benefits.
3. Write a detail note on Types of Enterprise Bean.
4. What are the ways to access Enterprise Beans? (Remote, Local and No-Interface)
5. How to access all types of interfaces in Enterprise Beans?
6. Describe packaging of Enterprise Beans.
7. Explain Session Beans. When to use them?
8. Explain various types of Session Bean.
9. Write a detail note on Singleton Session Bean.
10. Write a detail note on Stateful Session Bean.
11. Write a detail note on Stateless Session Bean.
12. Explain the lifecycle of Stateful session Bean.
13. Explain the lifecycle of Stateless Session Bean.
14. Explain the lifecycle of Singleton Session Bean.
15. Explain the lifecycle of Message Driven Bean.
16. Explain Message Driven Beans along with its uses.
17. Explain different classes imported in Message Driven Bean.
18. Explain onMessage() method of Message Driven Beans.
19. How to define Interceptor? What is the role of AroundInvoke method?
20. Explain Life cycle of Interceptor.
21. Define and Explain Java Naming and Directory Interface(JNDI).
22. What is Naming Service and Directory Service?
23. Explain basic Lookup in JNDI.
24. Write short on JNDI namespace in Java EE 7.
25. Write a short note on the following:
a. Resources and JNDI
b. Resource Injection
26. What is DataSource Resource Defination in Java EE7?
MCQs
1. Which services are provided to EJB components by the EJB container?
a. Transaction support
b. Persistence support
c. Naming support
d. All mentioned above
2. A message driven bean is like stateful session bean that encapsulates the business
logic and doesn't maintain state.
36
Compiled by: Beena Kapadia
a. True
b. False
4. JMS is mainly used to send and receive message from one application to another.
a. True
b. False
5. Which session bean maintain their state between client invocations but are not
required to maintain their state across server crashes or shutdowns?
6. Which EJB container must provide an implementation of Java Naming and Directory
Interface (JNDI) API to provide naming services for EJB clients and components?
a. Transaction support
b. Persistence support
c. Naming support
d. All mentioned above
a. True
b. False
9. The life cycle of session bean is not maintained by the application server (EJB
Container).
a. True
b. False
a. Security
b. Transaction Management
37
Compiled by: Beena Kapadia
c. Both A & B
d. None of the above
answers
1-d, 2- b, 3-a, 4-a, 5- c, 6-c, 7-b, 8-a, 9-b, 10 -c
38
Compiled by: Beena Kapadia