通过Hessian我们可以暴露服务端接口实现给远程客户端调用(比ejb简单),下面上例子
服务端:在eclipse中新建web工程
1.接口定义
IHelloService.java
public interface IHelloService {
public String sayHello(String name);
}
2.接口实现
IHelloServiceImpl.java
public class IHelloServiceImpl implements IHelloService {
@Override
public String sayHello(String name) {
return "Hello "+name;
}
}
3.web.xml定义
<?xml version="1.0" encoding="UTF-8" ?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>helloService</servlet-name>
<servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
<init-param>
<param-name>home-class</param-name>
<param-value>com.wangbo.hello.IHelloServiceImpl</param-value>
</init-param>
<init-param>
<param-name>home-api</param-name>
<param-value>com.wangbo.hello.IHelloService</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>helloService</servlet-name>
<url-pattern>/hessian/HelloService</url-pattern>
</servlet-mapping>
</web-app>
4.启动服务端
客户端实现
1.拷贝IHelloService接口
2.
import java.net.MalformedURLException;
import com.caucho.hessian.client.HessianProxyFactory;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
//testHelloService1();
testHelloService2();
}
private static void testHelloService1() {
String url = "http://localhost:8080/HessianServer//hessian/HelloService";
HessianProxyFactory factory = new HessianProxyFactory();
try {
IHelloService helloService = (IHelloService)factory.create(IHelloService.class, url);
System.out.println(helloService.sayHello("Hesssian"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private static void testHelloService2() {
String url = "http://localhost:8080/HessianServer//hessian/HelloService";
HessianProxyFactory factory = new HessianProxyFactory();
try {
IHelloService helloService = (IHelloService)factory.create(url);
System.out.println(helloService.sayHello("Hesssian"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
注意:
1.如果使用factory.create(IHelloService.class, url);则web.xml中无需配置
<init-param>
<param-name>home-api</param-name>
<param-value>com.wangbo.hello.IHelloService</param-value>
</init-param>
2.如果使用factory.create(url);则web.xml必须配置
<init-param>
<param-name>home-api</param-name>
<param-value>com.wangbo.hello.IHelloService</param-value>
</init-param>
否则报ClassNotFoundException
3.如果使用public class IHelloServiceImpl extends HessianServlet implements IHelloService{}的方式,需要依赖servlet-api.jar,同时web.xml配置要做调整