最近项目中涉及到外网平台调远程接口数据的问题,本来是用soap方式实现的,今天听人介绍了Hessian,想不到它的实现更加简单,代码写起来也比较少。
下面这个例子我是从Hessian官方上,稍微改了点。
创建一个名为Hessian的web工程,测试服务器为tomcat5.0,lib目录下必须包含hessian-3.0.20.jar包,下载地址:
http://www.ziddu.com/download/3556057/hessian-3.0.20.jar.rar.html
(1)接口Basic
package example;
public interface Basic {
public String hello(); //与服务端的hello方法对应
}
(2)服务端实现类
package example;
public class BasicService implements Basic {
private String _greeting = "Hello,ducklyl!";
public void setGreeting(String greeting)
{
_greeting = greeting;
}
public String hello()
{
return _greeting;
}
}
(3)客户端实现类
package example;
import com.caucho.hessian.client.HessianProxyFactory;
/**
* <p>Title: hessian实现远程调用</p>
* <p>Copyright: Copyright (c) 2007</p>
* @author ducklyl
* @version 1.0
*/
public class BasicClient {
public static void main(String []args)
throws Exception
{
String url = "http://127.0.0.1:8080/Hessian/ducklyl";
//创建factory实例
HessianProxyFactory factory = new HessianProxyFactory();
//客户端需实现Basic接口
Basic basic = (Basic) factory.create(Basic.class, url);
System.out.println("Hessian: " + basic.hello());
}
}
(4) web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>ducklyl</servlet-name>
<servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
<init-param>
<param-name>home-class</param-name>
<param-value>example.BasicService</param-value>
</init-param>
<init-param>
<param-name>home-api</param-name>
<param-value>example.Basic</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ducklyl</servlet-name>
<url-pattern>/ducklyl</url-pattern>
</servlet-mapping>
</web-app>
运行客户端程序BasicClient ,如果以下配置没问题,输出结果为:
Hessian: Hello,ducklyl!