hessian系列之一:Hello world

Hessian是一个WebService的轻量级二进制协议,使用起来比较简单。

随着信息技术的发展,不同语言或平台系统之间的交互越来越多,普通WebService使用起来会比较复杂,Hessian相对简单。

下面介绍下使用Hessian实现异构系统之间的数据交互:

Hessian构建服务和客户端一般需要如下四个步骤:

1.定义接口API

2.服务端实现-实现接口

3.客户端实现-HessianProxyFactory

4.在serlvet容器中配置服务

一、新建mavenweb工程,在pom.xml中加入hessian依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.john.hessian</groupId>
  <artifactId>hessian</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>hessian Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
	<junit.version>4.10</junit.version>
	<hessian.version>4.0.7</hessian.version>
	<logback.version>1.0.11</logback.version>
  </properties>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
	<dependency>
	  <groupId>com.caucho</groupId>
	  <artifactId>hessian</artifactId>
	  <version>${hessian.version}</version>
	</dependency>
	<dependency>
	  <groupId>ch.qos.logback</groupId>
	  <artifactId>logback-classic</artifactId>
	  <version>${logback.version}</version>
	</dependency>
  </dependencies>
  <build>
    <finalName>hessian</finalName>
  </build>
</project>

二、接口API:

public interface BasicAPI {
	String hello();
}

三、服务端实现:

public class BasicService implements BasicAPI {
	private String _greeting = "Hello world!";
	
	public void setGreeting(String greeting) {
		this._greeting = greeting;
	}

	@Override
	public String hello() {
		return _greeting;
	}
}

在web.xml加入:

<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>com.john.hessian.impl.BasicService</param-value>
    </init-param>
    <init-param>
      <param-name>home-api</param-name>
      <param-value>com.john.hessian.intf.BasicAPI</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

四、客户端实现:

public class BasicClient {
	static final String url = "http://localhost/hessian/hello";

	public static void main(String[] args) throws MalformedURLException {
		HessianProxyFactory factory = new HessianProxyFactory();
		BasicAPI basic = (BasicAPI) factory.create(BasicAPI.class, url);
		System.out.println("hello(): " + basic.hello());
	}
}

启动web工程,查看是否报错。

启动BasicClient,查看控制台输出的信息。

相关推荐