Saturday, August 13, 2005

another EJB3 container

Resin-3.0.14, another open source EJB 3 container. Though it is in beta version, it is really good for academic purpose. Since EJB 3 has become extraordinarily simple, it would take some mins to deploy your EJBs. I deployed a simple stateless session bean, similar to the one coming with the Resin, have uploaded the same, might be useful for you to get started.

In EJB3, there are no mandatory interfaces like, EJBHome and EJBObject, you may just have some business interface:
public interface Calculator {

public int add(int a, int b);

public int sub(int a, int b);

}


Bean implementation:
import static

javax.ejb.TransactionAttributeType.SUPPORTS;

@javax.ejb.Stateless
// Marks the bean as Stateless

public class CalculatorBean

implements Calculator {

@javax.ejb.TransactionAttribute(SUPPORTS)
//Marks the method with

//Supports transaction attribute

public int add(int a, int b)

{

return a+b;

}



@javax.ejb.TransactionAttribute(SUPPORTS)
//Marks the method with

//Supports transaction attribute

public int sub(int a, int b)

{

return a-b;

}

}


I could manage only to write the client as a Servlet, there is no proper documentation which describes how to write a standalone client. If anyone have used Resin to deploy prior versions of EJB, they can help us out with this. Anyhow found out that, we need to use either Burlap or Hessian implementations to expose the EJB to outside the container. Nevertheless, the ejb client servlet is:

public class ClientServlet extends HttpServlet {

private Calculator calc;

/**

* Dependency injector

* for the Calculator interface.

*/

@EJB(name="CalculatorBean")

public void setCalculator(Calculator newCalc)

{

calc = newCalc;

}

public void service(HttpServletRequest req,

HttpServletResponse res)

throws IOException, ServletException

{

PrintWriter out = res.getWriter();

if (calc == null) {

out.println("Calculator not found!");

return;

}

out.println("Add: "+calc.add(4,5));

out.println("Sub: "+calc.sub(4,5));

}

}

The above setCalculator method basically looks up the JNDI with "CalculatorBean" name , finds and assigns the instance. All it does since it is marked with @EJB annotation.

The configuration is pretty simple, just need to add <ejb-server> tag to web.xml:
<web-app xmlns="http://caucho.com/ns/resin">



<ejb-server jndi-name="java:comp/env/ejb">

<bean type="stateless.CalculatorBean"/>

</ejb-server>



<servlet servlet-name="calc"

servlet-class="stateless.ClientServlet">

<load-on-startup>0</load-on-startup>

</servlet>



<servlet-mapping url-pattern="/calc"

servlet-name="calc"/>

</web-app>

0 comments: