欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Calling EJB3 deployed in Websphere AS7 from Standalone Java client ejb3javawebsphere 

程序员文章站 2024-03-21 10:39:22
...
1、先编写EJB3:

业务接口FirstEJBService
package com.first;

public interface FirstEJBService {
 void print(String msg);
}


EJB Local接口FirstEJBServiceBeanLocal
package com.first;

import javax.ejb.Local;

@Local
public interface FirstEJBServiceBeanLocal extends FirstEJBService {
}


EJB Remote接口FirstEJBServiceBeanRemote
package com.first;

import javax.ejb.Remote;

@Remote
public interface FirstEJBServiceBeanRemote extends FirstEJBService {
}


业务实现类FirstEJBServiceBean
package com.first;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

@Stateless(mappedName = "FirstEJBServiceBean")
@Local({ FirstEJBServiceBeanLocal.class })
@Remote({ FirstEJBServiceBeanRemote.class })
public class FirstEJBServiceBean implements FirstEJBService {

	@Override
	public void print(String msg) {
		System.out.println("FirstEJBService echo : " + msg);
	}

}


2、打包成jar后,发布到Websphere中;

3、查看JNDI
在cmd下调用WebSphere\AppServer\bin目录中dumpNameSpace.bat,可以查看到所有的JNDI,找到该EJB对应的JNDI全称;

4、编写Standalone Java client
package com.ejbclient.first;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.first.FirstEJBService;

public class FirstEJBClient {

	/**
	 * @param args
	 * @throws NamingException
	 */
	public static void main(String[] args) throws NamingException {
		Properties env = new Properties();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.ibm.websphere.naming.WsnInitialContextFactory");
		env.put(Context.PROVIDER_URL, "iiop://localhost:2809");
		InitialContext context = new InitialContext(env);

		Object result = context
				.lookup("ejb/FirstEJB/FirstEJB.jar/FirstEJBServiceBean#com.first.FirstEJBServiceBeanRemote");

		FirstEJBService service = (FirstEJBService) javax.rmi.PortableRemoteObject
				.narrow(result, FirstEJBService.class);

		service.print("Hello EJB");
	}

}



client中,需要com.ibm.websphere.naming.WsnInitialContextFactory类,该类存在于WebSphere\AppServer\runtimes目录下的com.ibm.ws.admin.client_7.0.0.jar中,运行的时候需要在classpath中加上该jar;

到这并没有结束,由于Client与EJB不在同一个JVM中,所以还需要调用WebSphere\AppServer\bin目录中createEJBStubs.bat创建EJB stub:
createEJBStubs.bat com.first.FirstEJBService  -cp .


在运行的时候,将createEJBStubs.bat产生的_FirstEJBService_Stub.class放入classpath中,否则会产生异常:
java.lang.ClassCastException: org.omg.stub.java.rmi._Remote_Stub incompatible with com.first.FirstEJBService

或者
Exception in thread "P=556551:O=0:CT" java.lang.ClassCastException: Unable to load class: com.first._FirstEJBService_Stub