首页 > 代码库 > Hessian入门案例

Hessian入门案例

1.1.  Hessian简介

Hessian:hessian是一个轻量级的remoting onhttp工具,使用简单的方法提供了RMI的功能,相比WebService,Hessian更简单、快捷。采用的是二进制RPC协议,因为采用了二进制协议,所以它很适合于发送二进制数据,Hessian主要作面向对象的消息通信。

1.2.  开发步骤

1.2.1.   导入jar包

去官网下载http://hessian.caucho.com/

1.2.2.   编写远程接口

Ihello.java

 

package cn.tempus.hessian;

 

public interface IHello {

  

   public String sayHello(String name);

  

 

}

1.2.3.   编写远程接口实现类

HelloImpl.java需要继承HessianServlet

package cn.tempus.hessian;

 

import com.caucho.hessian.server.HessianServlet;

 

public class HelloImpl extends HessianServlet implements IHello {

 

   private static final long serialVersionUID = -6448991611447150108L;

 

   public String sayHello(String name) {

      return "Hello: "+name;

   }

 

}

 

1.2.4.   Web.xml文件中配置servlet

Web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>HessianDemo</display-name>

  <servlet>

    <servlet-name>Hello</servlet-name>

    <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>

    <init-param>

      <param-name>home-class</param-name>

      <param-value>cn.tempus.hessian.HelloImpl</param-value>

    </init-param>

    <init-param>

      <param-name>home-api</param-name>

      <param-value>cn.tempus.hessian.IHello</param-value>

    </init-param>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>Hello</servlet-name>

    <url-pattern>/Hello</url-pattern>

  </servlet-mapping>

 

 

</web-app>

1.2.5.   编写客户端

Client.java

package cn.tempus.hessian;

 

import java.net.MalformedURLException;

 

import com.caucho.hessian.client.HessianProxyFactory;

 

public class Client {

 

   public static String url = "http://127.0.0.1:8080/HessianDemo/Hello";

 

   public static void main(String[] args) {

      HessianProxyFactory factory = new HessianProxyFactory();

      try {

         IHello iHello = (IHello) factory.create(IHello.classurl);

         System.out.println(iHello.sayHello("morris"));

      } catch (MalformedURLException e) {

         e.printStackTrace();

      }

   }

 

}

 

1.2.6.   发布项目到jetty

Jetty后台打印

Running Jetty 6.1.26

2014-12-29 16:09:27.234:INFO::Logging to STDERR via org.mortbay.log.StdErrLog

ParentLoaderPriority enabled

Context path:/HessianDemo

ProjectClassLoader: entry=D:\Morris\javaPrj\HessianDemo\build\classes

ProjectClassLoader: entry=D:\Morris\javaPrj\HessianDemo\WebContent\WEB-INF\lib\hessian-4.0.37.jar

2014-12-29 16:09:27.500:INFO::jetty-6.1.26

2014-12-29 16:09:29.328:INFO::Started SelectChannelConnector@0.0.0.0:8080

 

1.2.7.   运行客户端

结果如下:

Hello: morris

 

Hessian入门案例