Why use EJB when we can do the same thing with servlets?

Dan Christopherson

Actually, servlets/JSPs and EJB are complementary, not competing technologies: Servlets provide support for writing web based applications whereas EJBs provide support for writing transactional objects. In larger web systems that require scalability, servlet and JSP or XML/XSL technologies provide support for the front end (UI, client) code, where EJB provides support for the back end (database connection pooling, declaritive transactions, declaritive security, standardized parameterization...)

The most significant difference between a web application using only servlets and one using servlets with EJBs is that the EJB model mandates a separation between display and business logic. This is generally considered a Good Thing in non-trivial applications because it allows for internal reuse, allows flexibility by providing a separation of concerns, gives a logical separation for work, and allows the business logic to be tested separately from the UI (among others).

Some of the hings that servlets and JSPs can do that EJBs cannot are:

  • Respond to http/https protocol requests.
  • (With JSP) provide an easy way to format HTML output.
  • Easily associate a web user with session information

Some of the things that EJBs enable you to do that servlets/JSPs do not are:

  • Declaritively manage transactions. In EJB, you merely specify whether a bean's methods require, disallow, or can be used in the context of a transaction. The EJB container will manage your transaction boundaries appropriately. In a purely servlet architecture, you'll have to write code to manage the transaction, which is difficult if a logical transaction must access multiple datasources.
  • Declaritively manage security. The EJB model allows you to indicate a security role that the user must be assigned to in order to invoke a method on a bean. In Servlets/JSPs you must write code to do this. Note, however that the security model in EJB is sufficient for only 90% to 95% of application code - there are always security scenarios that require reference to values of an entity, etc.