通过网络从客户端远程访问EJB

时间:2014-09-09 09:14:12

标签: java java-ee glassfish ejb cdi

假设有CLI或Swing接口客户端,如何通过Glassfish访问远程Bean?截至obtaining a reference to BeanManager

示例代码:

Hashtable contextArgs = new Hashtable();

// First you must specify the context factory.
// This is how you choose between jboss implementation
// vs. an implementation from Sun or other vendors.
contextArgs.put( Context.INITIAL_CONTEXT_FACTORY, "com.jndiprovider.TheirContextFactory" );

// The next argument is the URL specifying where the data store is:
contextArgs.put( Context.PROVIDER_URL, "jndiprovider-database" );

// (You may also have to provide security credentials)

// Next you create the initial context
Context myCurrentContext = new InitialContext(contextArgs);

http://en.wikipedia.org/wiki/Java_Naming_and_Directory_Interface#Basic_lookup

因此,对于访问正在运行的glassfish应用服务器的CLI应用程序,它将使用以下内容:

    Context context = null;
    try {
        context = new InitialContext();
        hello = (Hello) context.lookup("java:global/SalutationApp/SalutationApp-ejb/Hello");
        hello.myRemoteMethod();
    } catch (Exception e) {
        e.printStackTrace();
    }

仅使用指定的URL连接到特定的glassfish实例?如何建立连接?

1 个答案:

答案 0 :(得分:1)

如果您正在进行真正的远程查找,则无法通过CDI BeanManager执行此操作,因为Swing GUI不是本地的。

首先,您需要配置应用程序服务器以允许远程调用 - 这很可能包括一些身份验证设置,但我从未在Glassfish上执行此操作。

以下是我们在一个访问JBoss 4上部署的EJB的Swing应用程序中查找EJB bean远程接口的方法。

首先,我们在UI的ClassPath中添加了一个jndi.properties,其中包含服务器负责命名查找的信息(请注意,端口号是特定于应用程序服务器的)。这是我们自己的Swing GUI中使用的jndi.properties文件:

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=server.local\:1199

接下来,鉴于您的命名上下文现在知道如何查找远程JNDI名称,您可以使用类似的东西(再次,这在我们的Swing UI中使用):

InitialContext ctx = new InitialContext();
MyRemote mr = (MyRemote) ctx.lookup("global/jndi/name/of/remote/interface");

您也可以通过在代码中传递配置值来配置InitialContext,而不是使用属性文件,如下所示:

    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory"); // depends on your server
    env.setProperty(Context.PROVIDER_URL, "jnp://server.local:1099/");
    env.setProperty(Context.SECURITY_PRINCIPAL, "user"); 
    env.setProperty(Context.SECURITY_CREDENTIALS, "password");
    InitialContext ctx = new InitialContext(env);  

这个答案并不完整,但我希望这有助于您入门。