`
yinxvxv
  • 浏览: 50947 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论
阅读更多

hessian是一个轻量级的Java Remoting方案
1.在服务器端公开一个接口
2.在客户端通过url来访问这个接口

下面是一个简单的例子:
1.服务器端开发
在myeclipse下建一个web工程hessian
将hessian-3.0.13.jar包拷到WebRoot/WEB-INF/lib下
写一个接口HelloService.java

package com.test.service;

public interface HelloService {
 public String sayHello(String name);
}

 
写一个实现类HelloServiceImpl.java

package com.test.service.impl;

import com.test.service.HelloService;

public class HelloServiceImpl implements HelloService {
 public String sayHello(String name) {
  return "Hello," + name;
 }
}

 
在web.xml中公开你的接口(用hession中的servlet来实现),即加入下面代码:

<servlet>
 <servlet-name>service</servlet-name>
 <servlet-class>
  com.caucho.hessian.server.HessianServlet
 </servlet-class>
 <init-param>
  <param-name>home-api</param-name>
  <param-value>com.test.service.HelloService</param-value>
 </init-param>
 <init-param>
  <param-name>home-class</param-name>
  <param-value>com.test.service.impl.HelloServiceImpl</param-value>
 </init-param>
</servlet>

<servlet-mapping>
 <servlet-name>service</servlet-name>
 <url-pattern>/service/*</url-pattern>
</servlet-mapping>

 
将该工程发部到tomcat6.0下,启动服务器,服务器端开发完毕.
2.客户端开发
在myeclipse下建一个java工程hessionClient
把hessian-3.0.13.jar设为架包(具体方法:在工程下新建一个文件夹lib,将hessian-3.0.13.jar粘贴进来,选择该包右建,选择Build Path->Add Build Path)
写一个和服务器上接口一样的接口HelloService.java

package com.test.service;

public interface HelloService {
 public String sayHello(String name);
}

 
写一个测试入口Client.java

package com.test.client;

import java.net.MalformedURLException;
import com.caucho.hessian.client.HessianProxyFactory;
import com.test.service.HelloService;

public class Client {
 public static void main(String[] args) {
  try {
   String url = "http://127.0.0.1:8080/hessian/service";
   HessianProxyFactory hessianProxy = new HessianProxyFactory();
   hessianProxy.setReadTimeout(10000);
   HelloService helloService = (HelloService) hessianProxy.create(HelloService.class, url);
   System.out.println(helloService.sayHello("xvxv"));
  } catch (MalformedURLException e) {
   e.printStackTrace();
  }
 }
}

 
运行它,结果显示"Hello,xvxv",实例成功.

在客户端没有实现类,只有接口,真正执行的代码是服务器上的实现类.
附件里有该例代码.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics