6) Enterprise JavaBean (EJB) components
6) Enterprise JavaBean (EJB) components
Programming
Chapter 6 – Enterprise JavaBean (EJB) components
MARSHIMA MOHD ROSLI
COMPUTER SCIENCE
Enterprise JavaBean (EJB) components
❑Define Java Bean - create java bean
❑ Describe the custom bean properties and
Chapter 6 events
Outline ❑Describe types of EJB - session beans, entity
beans and message driven beans
Introduction to JavaBeans
What are JavaBeans?
◦ Software components written in Java
◦ Connect and Configure Components
◦ Builder Tools allow connection and configuration of Beans
◦ Begins ‘Age of Component Developer’
◦ Bringing Engineering methods to Software Engineering (e.g. electronics…)
Definitions Java Beans
❑A reusable software component that can be manipulated visually in a
‘builder tool’. (from JavaBean Specification)
❑The JavaBeans API provides a framework for defining reusable,
embeddable, modular software components.
❑Purpose: Store Data
❑Simple Object, requires no argument constructor
❑Properties accessible via get & set methods
Java Beans - example
For a "foo" property, a java bean will respond to
◦ Type getFoo()
◦ void setFoo(Type foo)
int getCount()
void setCount(int c)
String getS()
int count;
String s; void setS(String s)
int[] foo;
int[] getFoo()
void setFoo(int[] f)
// MagicBean.java
/* A simple bean that contains a single
* "magic" string.
*/
public class MagicBean {
private String magic;
public MagicBean(String string) {
magic = string;
}
public MagicBean() {
magic = "Woo Hoo"; // default magic string
}
public String getMagic() {
return(magic);
}
public void setMagic(String magic) {
this.magic = magic;
}
}
Java Beans
<jsp:useBean id="myBean" class="com.foo.MyBean“
scope="request"/>
<jsp:getProperty name="myBean“
property="lastChanged" />
<jsp:setProperty name="myBean“
property="lastChanged" value="<%= new Date()%>"/>
Example
◦ <jsp:usebean id="bean" class="MagicBean" />
◦ <jsp:getProperty name="bean" property="magic" />
<!-- bean.jsp -->
<hr>
<h3>Bean JSP</h3>
<p>
Behold -- I bring forth the magic property from the Magic Bean...
<table border=1>
<tr>
<td bgcolor=green><font size=+2>Woo</font> Hoo</td>
<td bgcolor=pink>
<font size=+3>
<td bgcolor=pink>
<font size=+3>
<!-- the following effectively does bean.getMagic() -->
<jsp:getProperty name="bean" property="magic" />
</font>
</td>
<td bgcolor=yellow>Woo <font size=+2>Hoo</font></td>
</tr>
</table>
<!-- pull in content from another page at request time with a relative URL ref
to another page -->
<jsp:include page="trailer.html" flush="true" />
public class HelloBean extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<html>");
out.println("<head>");
String title = "Hello Bean";
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=white>");
out.println("<h1>" + title + "</h1>");
out.println("<p>Let's see what Mr. JSP has to
contribute...");
request.setAttribute("foo", "Binky");
MagicBean bean = new MagicBean("Peanut butter sandwiches!");
request.setAttribute("bean", bean);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/bean.jsp");
rd.include(request, response);
rd.include(request, response);
out.println("<hr>");
out.println("</body>");
out.println("</html>");
}
// Override doPost() -- just have it call doGet()
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
Using JavaBeans in JSP
To create an instance for a JavaBeans component, use the
following syntax:
<jsp:useBean id="objectName"
scope="scopeAttribute“ class="ClassName" />
This syntax is equivalent to
<% ClassName objectName = new ClassName() %>
except that the scope attribute specifies the scope of the
object.
12
Scope Attributes
13
Scope Attributes
application Specifies that the object is bound to the client’s
session. Recall that a client’s session is
page automatically created between a Web browser
request and Web server. When a client from the same
browser accesses two servlets or two JSP pages
on the same server, the session is the same.
14
Scope Attributes
application The default scope, which specifies that the
session object is bound to the page.
request
15
Scope Attributes
application Specifies that the object is bound to the client’s
session request.
page
16
How Does JSP Find an Object
When <jsp:useBean id="objectName"
scope="scopeAttribute"
class="ClassName" /> is processed, the JSP
engine first searches for the object of the class with
the same id and scope. If found, the preexisting
bean is used; otherwise, a new bean is created.
17
Another Syntax for Creating a Bean
18
This example creates a JavaBeans component named Count and uses it to count the
Example: Testing Bean Scope
number of visits to a page.
19
<!-- TestBeanScope.jsp -->
<%@ page import = "chapter40.Count" %>
<jsp:useBean id="count" scope="application" class="chapter40.Count">
</jsp:useBean> package chapter40;
<HTML>
<HEAD> public class Count {
</HEAD>
<BODY> /** Return count property */
</H3> }
</BODY> }
</HTML> }
20
Getting and Setting Properties
By convention, a JavaBeans component provides the
get and set methods for reading and modifying its
private properties. You can get the property in JSP
using the following syntax:
<jsp:getProperty name="beanId“
property=“age" />
This is equivalent to
<%= beanId.getAge() %>
21
Getting and Setting Properties, cont.
22
Associating Properties with Input Parameters
Often properties are associated with input parameters. Suppose you
want to get the value of the input parameter named score and set it
to the JavaBeans property named score. You may write the following
code:
23
Associating Properties with Input Parameters,
cont.
This is cumbersome. JSP provides a convenient
syntax that can be used to simplify it as follows:
<jsp:setProperty name="beanId" property="score"
param="score" />
24
Associating All Properties
Often the bean property and the parameter have the same
name. You can use the following convenient statement to
associate all the bean properties in beanId with the
parameters that match the property names.
<jsp:setProperty name="beanId"
property="*" />
25
Example: Computing Loan Using JavaBeans
Use JavaBeans to simplify Example 40.3 by associating the bean properties with
the input parameters.
<!-- ComputeLoan.jsp -->
<html>
<head> Associating the bean
<title>ComputeLoan Using the Loan Class</title> properties with the
</head> input parameters.
<body>
Getting
<%@ page import = "chapter40.Loan" %>
<jsp:useBean id="loan" class="chapter40.Loan"></jsp:useBean>
<jsp:setProperty name="loan" property="*" />
Loan Amount: <%= loan.getLoanAmount() %><br>
Annual Interest Rate: <%= loan.getAnnualInterestRate() %><br>
Number of Years: <%= loan.getNumOfYears() %><br>
<b>Monthly Payment: <%= loan.monthlyPayment() %><br>
Total Payment: <%= loan.totalPayment() %><br></b>
</body>
</html>
26
Enterprise Java Beans
Types of EJB s are:
◦ Entity Beans
◦ They model: products, customers, data.
◦ They have a persistent state.
◦ They have been replaced with the Java Persistence API entities in
EE 6 (they exist in previous versions, prior to EE5).
◦ Session Beans
◦ They model: processes, coordinate the activities of EJBs
◦ Do not have a persistent state.
◦ Message Driven Beans ( these beans require usage of Java Message
Service API – JMS).
27
Enterprise Java Beans
Enterprise JavaBeans technology supports both transient
and persistent objects.
A transient object is called a session bean,
and a persistent object is called an entity bean.
28
Enterprise Java Beans
Entity Beans
Entity Beans
Entity Beans
that implement
that implement
container
bean managed
managed
persistence
persistence
29
Enterprise Java Beans
Session Beans
Stateful Session
Stateless Session Beans:
Beans: Specific to a
Any client can use client. Maintain
them information about
the client.
30
Session Beans vs. Entity Beans
Session Bean Entity Bean
◦ represent a business ◦ representation of
process, e.g. Billing credit persistent data
card, trading stocks. ◦ can be shared by multiple
◦ is associated with one clients
client and the life of the ◦ can read from DB and save
session bean is the life of back to DB
the customer. ◦ has much longer life and
◦ do not survive from the can survive from server
server crashes crashes
Activation vs. Passivation
Activation Passivation
◦ When a client needs to ◦ If too many beans are
use a bean that has been instantiated, EJB container
passivated, an activation can passivate some of
process occurred. them
◦ The state of the bean is ◦ the state of the bean is
swapped in from the saved in a persistent store
persistent storage or file and swapped out
Stateless vs. Stateful
Stateless Stateful
◦ no internal state ◦ possess internal state
◦ can be pooled to service ◦ need to hand activation
multiple client and passivation
◦ need not to handle ◦ examples: shopping cart
activation and passivation
◦ examples: calculator
Container Managed Persistent vs. Bean
Managed Persistent
Container Managed Bean Managed
◦ EJB container is ◦ Entity bean is responsible
responsible for saving and for saving bean’s state.
retrieving bean’s state ◦ Less adaptive than
◦ Independent of data container managed entity
source bean
◦ Easy to develop ◦ persistence need to be
hard coded into the bean
Example on JavaBean JSP
Lab exercise
Creating a Simple Web Application Using a MySQL Database.
Demonstrates how to create a simple web application that connects to
a MySQL database server.
https://netbeans.org/kb/docs/web/mysql-webapp.html