EJB Interview Questions with Answers

Q: What is the J2EE?
The J2EE is a set of coordinated specifications and practices that together enable solutions for developing, deploying and managing multi-tier server-centric applications.

Q) What is enterprise java bean? Why ejb?
A) It’s a collection of java classes and xml descriptor files bundled together as a unit. The java classes must provide certain rules and call back methods as per ejb specifications.
When the application is so complex and requires certain enterprise level services such as concurrency, scalability, transaction services, resource pooling, security, fail-over, load-balancing ejb is the right choice.

Q) New in EJB 2.1?
à Message-driven beans (MDBs): can now accept messages from sources other than JMS.
à EJB query language (EJB-QL): many new functions are added to this language: ORDER BY, AVG, MIN, MAX, SUM, COUNT, and MOD.
à Support for Web services: stateless session beans can be invoked over SOAP/HTTP. Also, an EJB can easily access a Web service using the new service reference.
à EJB timer service: a new event-based mechanism for invoking EJBs at specific times.
à Many small changes: support for the latest versions of Java specifications, XML schema, and message destinations.

Q) Application server & Web server
à A.S is a generalized server for running more than one application like ejb, rmi, jsp and servlets.
à W.S is for request, response paradigm. It takes the client request and send response back to the client and the connection is closed.
à A.S cannot process Http request, but takes the forwarded request from W.S and process the business logic and send the output to the W.S which it turns send to the client.
à W.S understands and supports only HTTP protocol whereas an Application Server supports HTTP, TCP/IP and many more protocols.
à A.S manage transactions, security, persistence, clustering, caching, but W.S cannot help in this regards. W.S takes only the Http request.
à A.S provides runtime environment for server side components, they provide middleware services such as resource pooling and network.

Q) What does Container contain?
A) 1. Support for Transaction Management, 2. Support for Security 3. Support for Persistence 4. Support for management of multiple instances (Instance passivation, Instance Pooling, Database connection pooling)
5. Life Cycle Management

Q) SessionBeans         
            Session beans are not persistence there are short lived beans. S.B can perform database operations but S.B it self is not a persistence objects. S.B are business process objects they implements business logic, business rules and workflow.

Q) Statefull Session Bean & Stateless Session Bean
Stateless Session Bean
Stateful Session Bean
Stateless session bean these are single request business process is one that does not require state to be maintained across method invocation. Stateless session bean cannot hold the state.
Statefull session bean is a bean that is designed to service business process that span multiple methods request/transaction, S.S.B can retain their state on the behalf of individual client.
There should be one and only one create method that to without any argument in the home interface.
There can be one or more create methods with or without arguments in the Home Interface.
Stateless session bean instance can be pooled. Therefore “n” number of beans can cater to n+1 number of clients.
Statefull session bean do not have pooling concept. Stateful bean will be given individual copy for every user.
Stateless bean will not be destroyed after client has gone.
Stateful bean will be destroyed once the client has gone (or after session time out)
If the business last only for a single method call, S.S.B are suitable
If the business process spans multiple invocations there by requiring a conversational then S.S.B will be ideal choice.
Stateless session bean cannot have instance variable
Stateful session bean will have instance variable and state is maintained in these instance variables
EjbRemove() method does not destroy the bean , it remains in the pooled state.
Stateful bean can be destroyed by calling the ejbRemove() method

Q) Entity Bean
            Entity beans are permanent business entities because their state is saved in permanent data storage. E.B are persistence objects, E.B contain data related logic. E.B are permanent so if any machine crashes, the E.B can be reconstructed in memory again by simple reading the data back in from the database.

Bean managed Persistence & Container managed Persistence
à B.P is an entity bean that must be persisted by hand, other words component developer must write the code to translate your in-memory fields into an underlying data store. You handle these persist operations your self, you place your data base calls in ejbLoad() and ejbStore(). Finder methods only for B.M.P for C.M.P your ejb container will implement the finder methods. In this commit, rollback, begin are transactions In B.M.P findByPK() return a reference to the actual bean object.
à You do not have to do anything to synchronize with database. In entity bean deployment descriptor you specify which fields that the container should manage. The transactions in C.M.P are TX-Support, TX-NotSupport, TX-require. He findByPK() in C.M.P return void because the method is internally implemented.

Q) Message Driven Bean
à M.D.B process messages asynchronously are deliver via JMS. M.D.B’s are stateless, server side, transaction aware components used for asynchronous JMS messages. It acts as a JMS message listener which JMS messages, the messages may be sent by any J2ee component, an application client, another enterprise bean, or by a JMS application.
     When EJB application server starts it parse the D.D and then loads and initializes declared beans. In case of M.D.B container establish a connection with the message provide(MOM server), client access message beans through the beans JMS interface (java.JMS.messageListerner) which exposes a single method.
Public void onmessage(javax.JMS.message message)

Q) Diff Statefull Session & Entity Bean?
            Both S.S.B & E.B undergo passivation and activation. The E.B have a separate ejbStore() callback for saving state during passivation & a separate ejbLoad() callback for loading state during activation. We do not need these callbacks for S.S.B because the container is simply uses object serialization to persist S.S.B fields.

Q) Diff MDB & Stateless Session beans?
- MDB’s process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls.
- MDB have no H.I / R.I, and therefore cannot be directly accessed by internal or external clients. Clients interact with MDB’s only indirectly, by sending a message to a JMS Queue or Topic.
- Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary
-The Container maintains the entire lifecycle of a MDB; instances cannot be created or removed as a result of client requests or other API calls.

Q) When to choose Statefull & Stateless Session bean?
A) Does the business process span multiple method invocations, requiring a conversational state if so the state full model fits very nicely. If your business process last for a single method call the stateless paradigm will better suite needed.

Q) When to choose Session Bean & Entity Bean?
à E.B are effective when application want to access one row at a time, if many rows needed to be fetched using session bean can be better alternative.
à E.B are effective when working with one row at a time cause of lot of N.W traffic. S.B are efficient when client wants to access database directly, fetching, updating multiple rows from database.
à S.B for application logic.

Q) When to choose CMP & BMP?
CMP is used when the persistent data store is a relational database and there is “one to one” mapping between a data represented in a table in the relational database and the ejb object.
Bean managed persistence is used when there is noone to one” mapping of the table and a complex query retrieving data from several tables needs to be performed to construct an ejb object. Bean managed is also used when the persistence data storage is not a relational database.

Q) How do Stateful Session beans maintain consistency across transaction updates?
A) S.S.B maintain data consistency by updating their fields each time a transaction is committed. To keep informed of changes in transation status, a S.S.B implements the SessionSynchronization interface. Container then calls methods of this interface as it initiates and completes transactions involving the bean.

Q) Can't stateful session beans persistent? Is it possible to maintain persistence temporarily in stateful sessionbeans?
A) Session beans are not designed to be persistent, whether stateful or stateless. A stateful session bean instance typically can't survive system failures and other destructive events.
Yes, it is possible using Handle.

Q) Object-Relational Mapping
            Mapping of objects to relational database is a technology called O.R.M. O.R.M is a persistence mechanism of persistence objects than simple object serialization.

Q) Deployment Descriptor       
D.D contains information for all the beans in the “ejb.jar” file. D.D enables ejb container to provide implicit services to enterprise bean components, these services can gain your bean with out coding. D.D is a XML file.

Q) ejbCreate()
            In stateless session bean can have only one ejbCreate() method it must take no arguments. Remember that ejbCreate() is essentially analogous to a constructor for ejb; it initializes an instance internal state variable. Because the stateless session bean has no client specific variables.

Q) Can a Session Bean be defined without ejbCreate() method?
The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method.

- The home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments.
- Stateful Session Beans can have arguments (more than one create method). Stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition

Q) Can I develop an Entity Bean without implementing the create() method in the home interface?
As per the specifications, there can be 'ZERO' or 'MORE' create() methods defined in an Entity Bean. In cases where create() method is not provided, the only way to access the bean is by knowing its primary key, and by acquiring a handle to it by using its corresponding finder method. In those cases, you can create an instance of a bean based on the data present in the table. All one needs to know is the primary key of that table. i.e. a set a columns that uniquely identify a single row in that table. Once this is known, one can use the 'getPrimaryKey()' to get a remote reference to that bean, which can further be used to invoke business methods.

Q) How do you determine whether two entity beans are the same?
A) By invoking the EntityBean.isIdentical method. This method should be implemented by the entity bean developer to determine when two references are to the same object.

Q) How can you capture if findBy method returns more than one row?
A) If finder method returns more than one row, create or instantiate an object (which has instance variable equal to number of columns to be stored) each time and add the object to vector that stores. Vector stores only the memory address not object reference. So every time when you instantiate and store object into vector a separate memory address will be allocated and the same is stored in the vector.

Q) Diff Context, InitialContext & SessionContext & EntityContext
javax.naming.Context is an interface that provides methods for binding a name to an object. It's much like the RMI Naming.bind() method.

javax.naming.InitialContext is a Context and provides implementation for methods available in the Context interface.

Where as SessionContext is an EJBContext object that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container.

There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean for the purpose of the EntityBean accessing the container details. In general, the EJBContext (SessionContext and EntityContext), AppletContext and ServletContext help the corresponding Java objects in knowing about its 'context' [environment in which they run], and to access particular information and/or service. Where as, the javax.naming.Context is for the purpose of 'NAMING'  [by the way of referring to] an object.

Q) Can i call remove() on a Stateless Session bean?
A) Yes, The life of a Stateless Session bean for a client is just till the execution of the method that the client would have called on the bean…after the execution of that method if the client calls another method, then a different bean is taken from the pool. So the container very well knows that a bean has finished its life for a client and can put it back in the pool.

Q) Can a Stateless Session Bean maintain state?
A) Yes, A Stateless Session bean can contain no-client specific state across client-invoked methods. For ex states such as socket connection, dbase connection, references to an EJBObject and so on can be maintained.

Q) How can I map a single Entity Bean to multiple tables?
A) If you use Bean-Managed Persistence(BMP), map the bean to tables manually. Consider applying the DAO design pattern to accomplish this.
     If you choose Container-Managed Persistence(CMP), use the vendors object/relational mapping tool to specify the mapping between your object state and the persistence schema.

Q) Can EJB handle transaction across multiple databases?
A) The transaction manager in EJB handling transaction across multiple databases. This is accomplished with multiple Entity beans handling to each database and a single session bean to manage a transaction with the Entity bean.

Q) Session Bean CallBack methods?
public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean
    public abstract void ejbActivate();
    public abstract void ejbCreate();
    public abstract void ejbPassivate();
    public abstract void ejbRemove();
    public abstract void setSessionContext(SessionContext ctx);

SessionContext à S.C is your beans gateway to interact with the container, S.C query the container about your current transactional state, your security state.


ejbPassivate( ) à  If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here, i.e. close socket connections..etc.

ejbActivate( ) à When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection

ejbRemove()à container wants to remove your bean instance it will call this method.

Q) Entity Bean CallBack methods?
public interface javax.ejb.EntityBean extends javax.ejb.EnterpriseBean
    public abstract void ejbActivate();
    public abstract void ejbLoad();
    public abstract void ejbPassivate();
    public abstract void ejbRemove();
    public abstract void ejbStore();
    public abstract void setEntityContext(EntityContext ctx);
    public abstract void unsetEntityContext();

Q) EJBContext Rollback Methods

EJBContext interface provides the methods setRollbackOnly() & getRollbackOnly().
setRollbackOnly( )àOnce a bean invokes the setRollbackOnly() method, the current transaction is marked for rollback and cannot be committed by any other participant in the transaction--including the container.
getRollbackOnly( ) à method returns true if the current transaction has been marked for rollback. This can be used to avoid executing work that wouldn't be committed anyway.

Q) How can I call one EJB from inside of another EJB?
A) EJB can be clients of another EJB’s it just works. Use JNDI to locate the Home Interface of the other bean, and then acquire an instance.

Q) Conversational & Non-conversational
Conversational is an interaction between the bean and client, stateless session bean is a bean that do not hold multi method conversation with clients. Stateless.S.B cannot hold state, Statefull.S.B can hold conversational with client that may span multiple method requests. 

Q) JNDI to locate Home Objects
H.O are physically located some where on the N.W, perhaps in the address space of the Ejb Container. For client to locate H.O, you must provide nick name for your beans H.O. Client will use this nick name to identify the H.O it wants, we will specify the nice name in the Deployment descriptor. Container will use this nick name, JNDI goes over the N.W to some directory service to look for the H.O.

Properties props = System.getProperties();
Context ctx = new InitialContext(props);
MyHome home = (MyHome)ctx.lookup(“MyHome”);
MyRemoteInterface remote = home.create();

Q) ejbCretae( ) & ejbPostCreate( )
à ejbCreate() is called just before the state of the bean is written to the persistence storage. After this method is completed a new record is created and written.
à ejbPostCreate() is called after the bean has been written to  the database and the bean data has been assigned to an Ejb object.

à All EJB classes should package in a JAR file, All web components pages, servlets, gif, html, applets, beans, ejb modules, classes should be packaged into WAR file. EAR file contain all the JAR & WAR files. Note that each JAR, WAR, EAR file will contain D.D

Q) What is the need of Remote and Home interface. Why cant it be in one?
The home interface is your way to communicate with the container, that is who is responsible of creating, locating even removing one or more beans. The remote interface is your link to the bean, that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and beans) and you need two different interfaces for accessing to both of them.

Q) Life cycle

Life cycle of a Stateful Session Bean

-          Stateful session bean has 3 states Does Not Exist, Method Ready Pool and Passivated states.
-          A bean has not yet instantiated when it is in the Does Not Exist Sate.
-          Once a container creates one are more instance of a Stateful Session bean it sets them in a Method Ready State. In this state it can serve requests from its clients. Like Stateless beans, a new instance is created(Class.newInstance()), the context is passed (setSessionContext()) and finally the bean is created with the ejbCreate().
-          ejbPassivate( )  If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here,ie,close socket connections..Etc.
-          ejbActivate( )  When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection


Life cycle of a Stateless Session Bean : -

-          A S.S.B has only two states: Does Not Exist and Method Ready Pool.
-          A bean has not yet instantiated when it is in the Does Not Exist Sate.
-          When the EJB container needs one are more beans, it creates and set then in the Method Ready Pool Sate. This happens through the creation of a new instance(Class.newInstance()), then it is set its context (setSessionContext()) and finally calls the ejbCreate() method.
-          The ejbRemove() method is called to move a bean from the Method Ready Pool back to Does Not Exist State.

Life cycle of Entity bean
-          Bean instance “Dose not exist” state represent entity bean instance that has not been instantiated yet.
-          To create a new instance container calls the newInstance() on entity bean class.
-          After step 2 E.B is in a pool of other E.Bs. At this point your E.B does not have any E.B data base data loaded into it and it does not hold any bean specific resources (socket & database connections) .If the container wants to reduce it’s pool size it can destroy your bean by calling unsetEntityContext() on your bean.
-          When the client wants to create some new data base data it calls a create() method on entity beans HomeObject. The container grabs the beans instance from the pool and the instance ejbCreate() method is called.
-          E.B to be kicked back to pool, if a client call ejbremove() method.
-          ejbPassivate( )  If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here, ie,close socket connections..etc.
-          ejbActivate( )  When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection


Life cycle of M.D.B

Does Not Exist
When an MDB instance is in the Does Not Exist state, it is not an instance in the memory of the system. In other words, it has not been instantiated yet.

The Method-Ready Pool
MDB instances enter the Method-Ready Pool as the container needs them. When the EJB server is first started, it may create a number of MDB instances and enter them into the Method-Ready Pool. (The actual behavior of the server depends on the implementation.) When the number of MDB instances handling incoming messages is insufficient, more can be created and added to the pool.

Transitioning to the Method-Ready Pool
When an instance transitions from the Does Not Exist state to the Method-Ready Pool, three operations are performed on it. First, the bean instance is instantiated when the container invokes the Class.newInstance() method on the MDB class. Second, the setMessageDrivenContext() method is invoked by the container providing the MDB instance with a reference to its EJBContext. The MessageDrivenContext reference may be stored in an instance field of the MDB.
Finally, the no-argument ejbCreate() method is invoked by the container on the bean instance. The MDB has only one ejbCreate() method, which takes no arguments. The ejbCreate() method is invoked only once in the life cycle of the MDB.

Q) Transaction Isolation levels

The transaction can read uncommitted data. Dirty reads, nonrepeatable reads, and phantom reads can occur. Bean methods with this isolation level can read uncommitted change.

The transaction cannot read uncommitted data; data that is being changed by a different transaction cannot be read. Dirty-reads are prevented; nonrepeatable reads and phantom reads can occur. Bean methods with this isolation level cannot read uncommitted data.

The transaction cannot change data that is being read by a different transaction.
Dirty reads and nonrepeatable reads are prevented; phantom reads can occur. Bean methods with this isolation level have the same restrictions as Read Committed and can only execute repeatable reads.

The transaction has exclusive read and update privileges to data; different transactions can neither read nor write the same data. Dirty reads, nonrepeatable reads, and phantom reads are prevented. This isolation level is the most restrictive.

Dirty-read à When your application reads data from a database that has not been committed to permanent storage yet.

Un-repeatable read à When a component reads some data from a database, but upon reading the data, the data has been changed. This can arise when another concurrently executing transaction modifies the data being read.

Phantom-read à Phantom is a new set of data that magically appears in a database between two databases read operations.

Q) Diff Phantom  & Un-repeatable
            Un-repeatable occurs when existing data is changed, where as phantom read occurs when new data is inserted that does not exist before.

Q) Transaction Attributes

TX_BEAN_MANAGED à Then your bean programmatically controls its own transaction boundaries. When you using programmatically transaction, you issue the begin, commit & abort statements.

TX_NOT_SUPPORTED à If you set this your bean cannot be involved in a transaction at all.

TX_REQUIRED à If you want your bean to always run in a transaction. If there is a transaction already running your bean joins in on that transaction. If there is no transaction running, the container starts one for you.

TX_REQUIRES_NEW à If you always want a new transaction to begin when your bean is called we should use this. If there is a transaction already underway when your bean called, that transaction is suspended during the bean invocation. The container then launches a new transaction and delegate the call to the bean.

TX_SUPPORTS à When a client call this it runs only in a transaction if the client had one running already; it then joins that transaction. If no transaction, the bean runs with no transaction at all.

TX_MANDATORY à Is a safe transaction attribute to use. It guarantees that your bean should run in a transaction. There is no way your bean can be called if there is not a transaction already running.

Q) ACID Properties
            When you properly use transaction your operations will execute ACID properties.

Atomicity à Guarantees that many operations are bundled together and appears as one contiguous unit of work.
Ex:- When you transfer money from one bank account to another you want to add funds to one account and remove funds from the other transaction and you want both operations to occur or neither to occur.

Consistency à Guarantees that a transaction will leave the system state to be consistent after a transaction completes.
Ex: - A bank system state could be consist if the rule “bank account balance must  always be +ve”.

Isolation à Protect concurrently executing transaction from seeing each other incomplete results.
Ex: - If you write a bank account data to a database, the transaction may obtain locks on the bank account record (or) table. The lock guarantee that no other updates can interfere.

Durability à Resources keep a transactional log for resources crashes; the permanent data can be reconstructed by reapplying the steps in the log.

Q) Diff Sax & DOM
  1. Tree of nodes
  2. Occupies more memory preferred for small XML documents
  3. Slower at runtime
  4. Stored as objects
  5. Programmatically easy, since objects
  6. Easy of navigation
  7. DOM creates a tree structure in memory

1.Sequence of events
2.Does not use any memory preferred for large documents.
3.Faster at runtime
4.Objects are to be created
5.Need to write code for creating objects are to referred
6.backward navigation is not possible

Q) Hot deployment
Hot Deployment in Web Logic is he acts of deploying, re-deploying and un-deploying EJBs while the server is still running.

Q) When should I use TxDataSource instead of Datasource?
  If your application  (or) environment meets the following criteria you should use
- Uses JTA
- Uses EJB container in web logic server to manage transactions.
- Includes multiple database updates with single transaction.
- Access multiple resources, such as database & JMS during transactions.
- Use same connection pool on multiple servers.

Q) Clustering
            In J2ee container can be distributed, a distributed container consists of number of JVM’s running on one are more host machines. In this setup, application components can be deployed on a number of JVM’s. Subject to the type of loading strategy and the type of the component the container can distributed the load of incoming request to one of these JVM’s.

Q How to deploy in J2EE (i.e Jar, War file)?

Each web application should be contained in a war (web archive) file. War files are nothing but a jar file containing atleast one descriptor called web.xml. The file structure of war file is:

    | WEB-INF
    |   |
    |   |-- WEB.XML (Deployment descriptor)
    |   |-- classes (Folder containing servlets and JSPs
    | META-INF
    |   |
    |   |-- MANIFEST.MF
    | all utility files and resources like error pages etc.

Each enterprise bean is stored in a jar file. The jar file contains all standard files like manifest and atleast one additional file called ejb-jar.xml. The structure of a jar file is:

    | META-INF
    |   |
    |   |-- MANIFEST.MF
    |   |-- ejb-jar.xml
    | all classes as in a normal jar file.

Both jar and war files are placed inside a ear (enterprise archive) file. The structure of an ear file is

    | META-INF
    |   |
    |   |-- MANIFEST.MF
    |   |-- application.xml
    | jar and war files.

Q) How do you configure a session bean for bean-managed transactions?
A) By set transaction-attribute in the xml file or in the deployment descriptor.

Q) Deployment descriptor of EJB (ejb-jar.xml)
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise
JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">

    This Deployment includes all the beans needed to make a reservation:
    TravelAgent, ProcessPayment, Reservation, Customer, Cruise, and Cabin.
<! – Transactions in EJB -- >
            <method-name>methodName / *</method-name>

Q) Weblogic-ejb-jar.xml

Q) Session Bean Example

  Remote Interface
     public interface Hello extends javax.ejb.EJBObject
            public String hello() throws java.rmi.RemoteException;   

  Home Interface
    public interface HelloHome extends javax.ejb.EJBHome
            Hello create() throws java.rmi.RemoteException; javax.ejb.CreateException;       

 Bean Class
     public class HelloBean implements javax.ejb.SessionBean
            private SessionContex ctx;
public void ejbCreate();
            public abstract void ejbRemove();
public abstract void ejbActivate();
public abstract void ejbPassivate();
            public abstract void setSessionContext(SessionyContext ctx);
            public String hello(){
            Return “hello world”;

      public class HelloClient
            public static void main(String args[ ])
properties props = system.getProperties();
            Context ctx =  new InitialContext(props);
Object obj = ctx.lookup(“HelloHome”);
HelloHome home = (HelloHome)
javax.rmi.protableRemoteObject.narrow(obj, HelloHome.class);
            Hello hello = home.create();

Q) Entity Bean Example

Home.java  (Home Interface)
package test;

public interface Home extends javax.ejb.EJBHome {
public String hello() throws RemoteException;
            public int add(int a, int b) throws RemoteException;
public HomeObj findByPrimaryKey(String a) throws RemoteException, FinderException;

HelloObj.java (Remote Interface)
package test;

public interface HelloObj extends javax.ejb.EJBObject {

HelloBean.java (Bean class)
package test;
import javax.ejb.*;

public class HelloBean extends com.caucho.ejb.AbstractEntityBean {
  public String ejbHomeHello()
    return "Hello, world";

  public int ejbHomeAdd(int a, int b)
    return a + b;

  public String ejbFindByPrimaryKey(String key) throws FinderException
    throw new FinderException("no children");

package test.entity.home;
import javax.naming.*;

public class HomeServlet extends GenericServlet {
  Home home;

  public void init() throws ServletException
    try {
      Context env = (Context) new InitialContext().lookup("java:comp/env");
      home = (Home) env.lookup("ejb/home");
    } catch (Exception e) {
      throw new ServletException(e);

  public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException
    PrintWriter pw = res.getWriter();
     try {
      pw.println("message: " + home.hello() + "");
      pw.println("1 + 3 = " + home.add(1, 3) + "");
      pw.println("7 + 1 = " + home.add(7, 1) + "");
    } catch (Exception e) {
      throw new ServletException(e);

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email