Component invocations

Servlets in EAServer can instantiate component instances using the same technique used within EJB or Java/CORBA components. Use the EJB technique when portability to other J2EE servers is required.

Using the EJB technique

To invoke component methods, use the lookup method in class javax.naming.InitialContext to resolve the Bean’s home interface, then create a reference to the remote interface. For example:

import javax.ejb.*;
import javax.naming.*;

QueryBean _queryBean;
String _queryBeanName = 
   "java:comp/env/ejb/querybean" ;
Context ctx = getInitialContext();
try {
    Object h = ctx.lookup(_queryBeanName);
    QueryBeanHome qbHome = (QueryBeanHome)
    javax.rmi.PortableRemoteObject.narrow(h,        QueryBeanHome.class);
    _queryBean = qbHome.create();
} 
catch (NamingException ne) 
{
    System.out.println("Error: Naming exception: "
       + ne.getExplanation() + ne.toString());
    throw new Exception(
      "Lookup failed for EJB " + _queryBeanName);
}

For more information on the EJB client interfaces, see Chapter 8, “Creating Enterprise JavaBeans Clients.” You can define an EJB reference in the Web application properties to alias the servlet name used in your source code. The EJB reference allows the Web application to be deployed on another J2EE server without changing your servlet code. See “EJB references” for more information.

Using the Java/CORBA technique

To invoke component methods, create an ORB instance to obtain a proxy for the components, then invoke methods on the proxy object reference. For components on the same server, call the string_to_object method with the IOR string specified as Package/Component. For example, the fragment below obtains a proxy object for a component called Payroll that is installed in the Finance package:

java.util.Properties props = new java.util.Properties();
props.put("org.omg.CORBA.ORBClass",
                 "com.sybase.CORBA.ORB");
ORB orb = ORB.init((java.lang.String[])null, props);
Payroll payroll = 
PayrollHelper.narrow(orb.string_to_object(
                       "Finance/Payroll"));

By default, servlets run without a user name and password. A servlet client, authenticated by EAServer, runs with the client’s user name and password. If an unauthenticated servlet client invokes a component method, the component is instantiated without a user name and password. If roles limit access to a component or method and the servlet has no user name, a method invocation attempt fails. To specify a user name, use this syntax:

orb.string_to_object("iiop://0:0:user_name:password/Package/Component"));

You can retrieve the system user name and password with these methods in class com.sybase.CORBA.ORB, which both return strings:

When called from components, string_to_object returns an instance running on the same server if the component is locally installed; otherwise, it attempts to resolve a remote instance using the naming server.