Singleton Session Bean Example

CartBean.java File

This java file comes under ejbModule under EJB project
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 annotation create singleton 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
	public void remove() {
		contents = null;
	}
}

SingletonBean.java File

This java file comes under ejbModule under EJB project
package com.jtechies;

import java.util.Date;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Schedule;
import javax.ejb.Schedules;
import javax.ejb.Singleton;

/**
 * Session Bean implementation 
 * class SingletonBean
 */
@Singleton 
// This annotation create singleton session bean
public class SingletonBean {
	@EJB // @EJB is used to inject EJB's
    CartBean cartBean;
	private int amount;
	
 int total;
	@PostConstruct 
	// This annotation invoked method before the 
	// first business method is invoked on the 
	// enterprise bean and after all dependency 
	// injection has completed.
    private void initialize() {
        System.out.println("Singleton inited!");
    }
	@Lock(LockType.WRITE) 
	// This annotation is use for lock 
	// purpose and its attribute is LockType
    public void addPrice(int amount) {
		this.amount=amount;
        total += this.amount;
    }
	@Lock(LockType.READ) 
	// This annotation is use for lock 
	// purpose and its attribute is LockType
    public int getTotal() {      
        return total;
    }
}

ClientServlet.java File

This java(servlet) file comes under web project src folder
package com.jtechies;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
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.exception.BookException;

@WebServlet("/ClientServlet")
public class ClientServlet 
extends HttpServlet {
	private static final long 
	serialVersionUID = 1L;

    @EJB
    CartBean cartBean;
    @EJB
    SingletonBean singletonBean;
    
    public ClientServlet() {
        super();
    }
    @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>
		Singleton Example!!</h2>");				
		try {
			cartBean.addBook("Stephen Covey");
			singletonBean.addPrice(450);
			cartBean.addBook("Scott Hommel");
			singletonBean.addPrice(720);
			cartBean.addBook("Tom Risser");
			singletonBean.addPrice(350);
			List<String> contents = 
			cartBean.getContents();
			for(String bookName : contents)
			{
				out.println
				("<h4> Book Found -> 
					"+bookName+"</h4>");
			}
			out.println("<h4>
			Total Received = 
				"+singletonBean.getTotal()+
				"</h4>");
		}
		catch(Exception e){
			e.printStackTrace();
		}
		out.println("</body>");
		out.println("</html>");
	}
}
Note :Now make new Enterprise Application project and add both EJB and Web project and run the Enterprise Application project for output.

Output


EJB Singleton output