Stateless Session Bean Example

SICalculator.java File

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

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
 * Session Bean implementation class SICalculator
 */
@Stateless 
// This annotation create stateless session bean
public class SICalculator {
	 @PostConstruct 
	 // This annotation invoked method before 
	 // the first business method is invoked 
	 // on the enterprise bean and after all 
	 // dependency injection has completed.
	    void show() {
	        System.out.println
	        ("SICalculator started...");
	    }
	    @PreDestroy 
	    // This annotation invoke method, when
	    // the bean is about to be destoryed by 
	    // EJB container
	    void remove(){
	        System.out.println
	        ("SessionEjbBean ended...");
	    }
	public double caculateSI
	(double priciple, double rate, int time ) {	
		return ((priciple * rate * time)/100) ;
	}

}

SessionServlet.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.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;

/**
 * Servlet implementation class SessionServlet
 */
@WebServlet("/SessionServlet")
public class SessionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB // @EJB is used to inject EJB's
	SICalculator calculator;   
	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>Stateless Example!!</h2>");
		try {
			out.println("<h4> Simple interest = 
			"+calculator.caculateSI(20000, 3, 2)+"</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 Stateless Output