Types of Enterprise Beans

EJB 3.0 defines two types of enterprise beans. These are:

  • Session bean : These types of beans directly interact with the client and contain business logic of the business application.
  • Message driven bean : It works like a listener or a consumer for a particular messaging service such as Java Message API.

Types of Session Beans

  • Stateful : This bean is similar to an interactive session. Stateful bean's existence is one per client and terminates when no longer associated with the client.
  • Stateless : This bean does not maintain conversational state with the client. Stateless beans are pooled to serve all clients and go back to pool when no longer associated with the client. Stateless beans offer better scalability because same bean instance has the capability to serve multiple clients. A stateless session bean can implement a web service, but a stateful session bean cannot.
  • Singleton : One per application and exists for the lifecycle of the application, as opposed to pool in case of Stateless. Like stateless, can be implement a web service.
    Useful in following scenario:
    • State needs to be shared across application.
    • Perform some tasks on application start-up and shutdown.

Stateful Session Bean Example

  • Step-1 Create EJB project by click on new >> other >> EJB >> EJB project.
  • Step-2 Create Session Bean by right click on ejbModule under EJB project >> other >> EJB >> Session Bean >> class name >> state type >> finish.

  • EJB Add Session Bean

CartBean.java File
package com.jtechies;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import com.jtechies.exception.BookException;

/**
 * Session Bean implementation class CartBean
 */
@Stateful // This annoatation create a stateful session bean 
public class CartBean {
	String customerName;
	String customerId;
	List<String> contents;

	public void initialize(String person) throws BookException {
		if (person == null) {
			throw new BookException("Null person not allowed.");
		} else {
			customerName = person;
		}
		customerId = "0";
		contents = new ArrayList<String>();
	}

	public void addBook(String title) {
		contents.add(title);
	}
	public void removeBook(String title) throws BookException {
		boolean result = contents.remove(title);
		if (result == false) {
			throw new BookException(title + " not in cart.");
		}
	}

	public List<String> getContents() {
		return contents;
	}

	@Remove // container will remove the enterprise 
		//bean method completes, either normally or abnormally
	public void remove() {
		contents = null;
	}
}
  • Step-3 Create class by right click on ejbModule under EJB project >> class >> class name >> finish.
BookException.java File
package com.jtechies.exception;

public class BookException extends Exception{
	
	public BookException(String exception){
		super(exception);
	}
}
  • Step-4 Create Dynamic Web project by click on new >> other >> web >> dynamic web project.
  • Step-5 Create Servlet by right click on src folder under java resources >> web >> servlet >> finish

  • EJB Add Servlet

ClientServlet.java File
package com.jtechies;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jtechies.CartBean;
import com.jtechies.exception.BookException;

/**
 * Servlet implementation class ClientServlet
 */
@WebServlet("/ClientServlet")
public class ClientServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB // @EJB is used to inject EJB's
    CartBean cartBean;   
    public ClientServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public void init(){
    	try {
			cartBean.initialize("Parker");
		} 
    	catch (BookException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	protected void doGet
		(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Login Page</title>");
		out.println("<body<");
		out.println("<h2>Stateful Example!!</h2>");
		try {
			cartBean.addBook("Stephen Covey");
			cartBean.addBook("Scott Hommel");
			cartBean.addBook("Tom Risser");
			List<String> contents = cartBean.getContents();
			for(String bookName : contents)
			{
				out.println("<h4> Book Found -> "+bookName+"</h4>");
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		out.println("</body>");
		out.println("</html>");
	}
}
  • Step-6 Now a dependency of EJB project to Web project by right click on web project >> properties >> java build path >> projects tab >> add >> select EJB project from the list >> press ok to finish.

  • EJB Add Dependency

  • Step-7 Create Enterprise Application Project by right click >> project >> java EE >> enterprise application project and add EJB and web project from the list.

  • EJB ADD EA Project

Output

EJB Stateful output