前提条件:已安装eclipse,并完成maven配置
1. 新建maven project,填好Artifact上的Group Id和Artifact Id,Packaging中选择pom
2. 新建两个maven module,分别是server和client
3. server中新建RemoteHelloWorld接口和HelloWorldBean类
//RemoteHelloWorld.java
package org.ejb.server;
/**
* @author chenjx
*
*/
public interface RemoteHelloWorld {
String sayHello(String name);
}
//HelloWorldBean.java
package org.ejb.server;
import javax.ejb.Remote;
import javax.ejb.Stateless;
/**
* @author chenjx
*
*/
@Stateless//无状态连接
@Remote(RemoteHelloWorld.class)//格式:接口.class
public class HelloWorldBean implements RemoteHelloWorld{
public String sayHello(String name) {
// TODO Auto-generated method stub
String str = "Hello " + name;
System.out.println(str);//这个在服务端输出
return str;//这个返回给调用该服务方法的客户端
}
}
4. client中新建HelloWorldClient类
//HelloWorldClient.java
package org.ejb.client;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.ejb.server.RemoteHelloWorld;
/**
* @author chenjx
*
*/
public class HelloWorldClient {
private static String name;
public static void main(String[] args) throws NamingException {
// TODO Auto-generated method stub
testSayHello();
}
private static void testSayHello() throws NamingException {
final RemoteHelloWorld hw = lookupRemoteHelloWorld();
name = "Chenjx";
String str = hw.sayHello(name);//调用服务端的方法并得到返回值
System.out.println(str);//在客户端输出返回值
}
private static RemoteHelloWorld lookupRemoteHelloWorld() throws NamingException{
final Hashtable<String, String> jndiProperties = new Hashtable<String, String>();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
return (RemoteHelloWorld) context.lookup("ejb:/ejb-server/HelloWorldBean!"+ RemoteHelloWorld.class.getName());
//格式:ejb:/服务端名/实现类名! + 接口名.class.getName()
}
}
5. 在client的根目录右键,新建文件夹src/main/resources, 并在该文件夹下添加文件jboss-ejb-client.properties
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=localhost
remote.connection.default.port = 8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POL