Java Beans
Java Beans
A JavaBean is a specially constructed Java class written in the Java and coded
according to the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java classes −
JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the
object. The attribute can be of any Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class −
setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only attribute will
have only a setPropertyName() method.
JavaBeans Example
Consider a student class with few properties −
package com.demo;
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}
Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean
becomes a scripting variable that can be accessed by both scripting elements and other
custom tags used in the JSP. The full syntax for the useBean tag is as follows −
Here values for the scope attribute can be a page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name
among other useBean declarations in the same JSP.
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that should be
invoked.
Following example shows how to access the data using the above syntax −
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "students" class = "com.demo.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value =
"Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>
</body>
</html>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the following
result will be displayed − Student First Name: Zara
Student Last Name: Ali
Student Age: 10
What is EJB
EJB is an acronym for enterprise java bean. It is a specification provided by Sun Microsystems to develop
secured, robust and scalable distributed applications.
To get information about distributed applications, visit RMI Tutorial first.
To run EJB application, you need an application server (EJB Container) such as Jboss, Glassfish, Weblogic,
Websphere etc. It performs:
EJB application is deployed on the server, so it is called server side component also.n
EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from Java Bean, RMI and
Web Services.
Session Bean
Session bean contains business logic that can be invoked by local, remote or webservice client.
Entity Bean
It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is replaced with JPA
(Java Persistent API).
Both RMI and EJB, provides services to access an object running in another JVM (known as remote object)
from another JVM. The differences between RMI and EJB are given below:
Advertisement
RMI EJB
RMI is built on the top of socket programming. EJB technology is built on the top of RMI.
In EJB, bean component and bean client both must be written in java language.
If bean client need to be written in other language such as .net, php etc, we need to go
with webservices (SOAP or REST). So EJB with web service will be better option.
Disadvantages of EJB
Session Bean
Session bean encapsulates business logic only, it can be invoked by local, remote and webservice client.
The life cycle of session bean is maintained by the application server (EJB Container).
Advertisement
1) Stateless Session Bean: It doesn't maintain state of a client between multiple method calls.
2) Stateful Session Bean: It maintains state of a client across multiple requests.
3) Singleton Session Bean: One instance per application, it is shared between clients and supports
concurrent access.
In other words, conversational state between multiple method calls is not maintained by the container in case of
stateless session bean.
The stateless bean objects are pooled by the EJB container to service the request on demand.
It can be accessed by one client at a time. In case of concurrent access, EJB container routes each request to
different instance.
1. @Stateless
2. @PostConstruct
3. @PreDestroy
There is only two states of stateless session bean: does not exist and ready. It is explained by the figure given
below.
EJB Container creates and maintains a pool of session bean first. It injects the dependency if then calls the
@PostConstruct method if any. Now actual business logic method is invoked by the client. Then, container
calls @PreDestory method if any. Now bean is ready for garbage collection.
To develop stateless bean application, we are going to use Eclipse IDE and glassfish 3 server.
To create EJB application, you need to create bean component and bean client.
Advertisement
File: AdderImplRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3.
4. @Remote
5. public interface AdderImplRemote {
6. int add(int a,int b);
7. }
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.ejb.Stateless;
3.
4. @Stateless(mappedName="st1")
5. public class AdderImpl implements AdderImplRemote {
6. public int add(int a,int b){
7. return a+b;
8. }
9. }
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.naming.Context;
3. import javax.naming.InitialContext;
4.
5. public class Test {
6. public static void main(String[] args)throws Exception {
7. Context context=new InitialContext();
8. AdderImplRemote remote=(AdderImplRemote)context.lookup("st1");
9. System.out.println(remote.add(32,32));
10. }
11. }
Output
Output: 64
In other words, conversational state between multiple method calls is maintained by the container in stateful
session bean.
1. @Stateful
2. @PostConstruct
3. @PreDestroy
4. @PrePassivate
5. @PostActivate
To develop stateful session bean application, we are going to use Eclipse IDE and glassfish 3 server.
As described in the previous example, you need to create bean component and bean client for creating session
bean application.
File: BankRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3. @Remote
4. public interface BankRemote {
5. boolean withdraw(int amount);
6. void deposit(int amount);
7. int getBalance();
8. }
File: Bank.java
1. package com.javatpoint;
2. import javax.ejb.Stateful;
3. @Stateful(mappedName = "stateful123")
4. public class Bank implements BankRemote {
5. private int amount=0;
6. public boolean withdraw(int amount){
7. if(amount<=this.amount){
8. this.amount-=amount;
9. return true;
10. }else{
11. return false;
12. }
13. }
14. public void deposit(int amount){
15. this.amount+=amount;
16. }
17. public int getBalance(){
18. return amount;
19. }
20. }
1. <form action="operationprocess.jsp">
2. Enter Amount:<input type="text" name="amount"/><br>
3.
4. Choose Operation:
5. Deposit<input type="radio" name="operation" value="deposit"/>
6. Withdraw<input type="radio" name="operation" value="withdraw"/>
7. Check balance<input type="radio" name="operation" value="checkbalance"/>
8. <br>
9. <input type="submit" value="submit">
10. </form>
File: operationprocess.jsp
1. package com.javatpoint;
2. import java.io.IOException;
3. import javax.ejb.EJB;
4. import javax.naming.InitialContext;
5. import javax.servlet.ServletException;
6. import javax.servlet.annotation.WebServlet;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. @WebServlet("/OpenAccount")
11. public class OpenAccount extends HttpServlet {
12. //@EJB(mappedName="stateful123")
13. //BankRemote b;
14. protected void doGet(HttpServletRequest request, HttpServletResponse response)
15. throws ServletException, IOException {
16. try{
17. InitialContext context=new InitialContext();
18. BankRemote b=(BankRemote)context.lookup("stateful123");
19.
20. request.getSession().setAttribute("remote",b);
21. request.getRequestDispatcher("/operation.jsp").forward(request, response);
22.
23. }catch(Exception e){System.out.println(e);}
24. }
25. }
Next Topic
Entity Bean
Entity bean represents the persistent data stored in the database. It is a server-side component.
In EJB 2.x, there was two types of entity beans: bean managed persistence (BMP) and container managed
persistence (CMP).
Since EJB 3.x, it is deprecated and replaced by JPA (Java Persistence API) that is covered in the hibernate
tutorial.