8.2. Retrieving a Home Interface and Creating a Bean

Here is an example on how to retrieve the home interface of a bean named Region from a Servlet and then create a new instance of this bean:

import java.io.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.*;
import javax.servlet.http.*;

public class RegionServlet extends HttpServlet
{
  /**
   * Called on a GET request for this servlet
   *
   * @param request a <code>HttpServletRequest</code> value
   * @param response a <code>HttpServletResponse</code> value
   * @exception IOException if an error occurs
   * @exception ServletException if an error occurs
   */
  public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws IOException, ServletException
  {
    private PrintWriter out;
    response.setContentType("text/html");
    try
    {
      out = reponse.getWriter();
    }
    catch (IOException ioe)
    {
      ioe.printStackTrace();
    }

    out.println("<!doctype html public 
      "-//w3c//dtd html 4.0 transitional//en">");
    out.println("<html>");
    out.println("<body>");
    out.println("RegionServlet - Looking for the initial context<br>")
     
    Context initialContext = null;
    try
    {
      initialContext = new InitialContext();
    } 
    catch (Exception e) 
    {
      out.println("RegionServlet - Cannot get initial context for JNDI: " 
      +e+"<br>");
      return ;
    }
    
    out.println("RegionServlet - Looking up bean's home interface<br>")
    
    RegionHome home;
    try 
    {
      home = (RegionHome)PortableRemoteObject.narrow(
      initialContext.lookup("java:comp/env/ejb/RegionHome"),
      RegionHome.class);
    } 
    catch (Exception e)
    {
      out.println("RegionServlet - Cannot lookup home interface: " 
      +e+"<br>");
      return ;
   } 
   
   out.println("RegionServlet - Creating a new bean instance<br>")
   
   Region bean;
   try 
   {
     bean = home.create();
   } 
   catch (Exception e)
   {
     sp.printHTML("RegionServlet - Error while creating new bean instance: " 
     +e+"<br>");
     return ;
   }
   
   ... here you can call any method defined in the bean 
       remote interface (example: bean.doSomething(...);) ...
   
   out.println("</body>\n");
   out.println("</html>\n");
  }

}