0% found this document useful (0 votes)
10 views11 pages

Java Beans

Uploaded by

bytemaster78
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)
10 views11 pages

Java Beans

Uploaded by

bytemaster78
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/ 11

JSP - JavaBeans

 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 −

 It provides a default, no-argument constructor.


 It should be serializable and that which can implement the Serializable interface.
 It may have a number of properties which can be read or written.
 It may have a number of "getter" and "setter" methods for the properties.

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 −

S.No. Method & Description


getPropertyName()
1 For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.

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 class StudentsBean implements java.io.Serializable {


private String firstName = null;
private String lastName = null;
private int age = 0;

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 −

<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>

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.

Following example shows how to use the useBean action −

<html>
<head>
<title>useBean Example</title>
</head>

<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>

You will receive the following result − −

The date/time is Thu Sep 30 11:18:11 GST 2010

Accessing JavaBeans Properties


Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the get
methods and the <jsp:setProperty/> action to access the set methods. Here is the full syntax −

<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">


<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>

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 First Name:


<jsp:getProperty name = "students" property = "firstName"/>
</p>

<p>Student Last Name:


<jsp:getProperty name = "students" property = "lastName"/>
</p>

<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:

a. life cycle management,


b. security,
c. transaction management, and
d. object pooling.

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.

When use Enterprise Java Bean?

1. Application needs Remote Access. In other words, it is distributed.


2. Application needs to be scalable. EJB applications supports load balancing, clustering and fail-over.
3. Application needs encapsulated business logic. EJB application is separated from presentation and
persistent layer.

Types of Enterprise Java Bean

There are 3 types of enterprise bean in java.

Session Bean
Session bean contains business logic that can be invoked by local, remote or webservice client.

Message Driven Bean


Like Session Bean, it contains the business logic but it is invoked by passing message.

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).

Difference between RMI and EJB

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

In RMI, middleware services such as security,


In EJB, middleware services are provided by EJB
transaction management, object pooling etc. need
Container automatically.
to be done by the java programmer.

RMI is not a server-side component. It is not EJB is a server-side component, it is required to


required to be deployed on the server. be deployed on the server.

RMI is built on the top of socket programming. EJB technology is built on the top of RMI.

EJB and Webservice

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

1. Requires application server


2. Requires only java client. For other language client, you need to go for webservice.
3. Complex to understand and develop ejb applications.

Session Bean
Session bean encapsulates business logic only, it can be invoked by local, remote and webservice client.

It can be used for calculations, database access etc.

The life cycle of session bean is maintained by the application server (EJB Container).

Types of Session Bean

There are 3 types of session bean.

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.

Stateless Session Bean


Stateless Session bean is a business object that represents business logic only. It doesn't have state (data).

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.

Annotations used in Stateless Session Bean

There are 3 important annotations used in stateless session bean:

1. @Stateless
2. @PostConstruct
3. @PreDestroy

Life cycle of Stateless Session Bean

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.

Example of Stateless Session Bean

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.

1) Create stateless bean component


To create the stateless bean component, you need to create a remote interface and a bean class.

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. }

2) Create stateless bean client


The stateless bean client may be local, remote or webservice client. Here, we are going to create remote client.
It is console based application. Here, we are not using dependency injection. The dependency injection can be
used with web based client only.

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

Stateful Session Bean


Stateful Session bean is a business object that represents business logic like stateless session bean. But, it
maintains state (data).

In other words, conversational state between multiple method calls is maintained by the container in stateful
session bean.

Annotations used in Stateful Session Bean

There are 5 important annotations used in stateful session bean:

1. @Stateful
2. @PostConstruct
3. @PreDestroy
4. @PrePassivate
5. @PostActivate

Example of Stateful Session Bean

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.

1) Create stateful bean component


Let's create a remote interface and a bean class for developing stateful bean component.

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. }

2) Create stateful bean client


The stateful bean client may be local, remote or webservice client. Here, we are going to create web based
client and not using dependency injection.
File: index.jsp

1. <a href="OpenAccount">Open Account</a>


File: operation.jsp

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. <%@ page import="com.javatpoint.*" %>


2. <%
3. BankRemote remote=(BankRemote)session.getAttribute("remote");
4. String operation=request.getParameter("operation");
5. String amount=request.getParameter("amount");
6.
7. if(operation!=null){
8.
9. if(operation.equals("deposit")){
10. remote.deposit(Integer.parseInt(amount));
11. out.print("Amount successfully deposited!");
12. }else
13. if(operation.equals("withdraw")){
14. boolean status=remote.withdraw(Integer.parseInt(amount));
15. if(status){
16. out.print("Amount successfully withdrawn!");
17. }else{
18. out.println("Enter less amount");
19. }
20. }else{
21. out.println("Current Amount: "+remote.getBalance());
22. }
23. }
24. %>
25. <hr/>
26. <jsp:include page="operation.jsp"></jsp:include>
File: OpenAccount.java

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.

You might also like