Hession可以非常方便完成基于Http协议的远程调用,以下是一个非常简单的示例代码,其中Server使用java实现而Client分别使用java和C#实现
(如果您使用vs2003而HessianCSharp需要vs2005,你可以直接引入代码,将不能编译的语句注释掉,然后运行示例--可以执行。)
Server:
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!--Definition of View Resolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!--Request Mapping -->
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
</bean>
<bean id="helloService" class="cj.domain.HelloService"></bean>
<bean name="/hello.do" class="org.springframework.remoting.caucho.HessianServiceExporter">
<property name="service">
<ref bean="helloService" />
</property>
<property name="serviceInterface">
<value>cj.domain.Hello</value>
</property>
</bean>
</beans>
--------------------------------------------------------------------------------
Hello.java
package cj.domain;
public interface Hello {
public String hello(String name);
}
HelloService.java
package cj.domain;
public class HelloService implements Hello {
public String hello(String name){
return "hello "+name+"!";
}
}
--------------------------------------------------------------------------------
Java Client:
clientContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<property name="serviceUrl">
<value>
http://localhost:8080/C3Java/hello.do
</value>
</property>
<property name="serviceInterface">
<value>cj.domain.Hello</value>
</property>
</bean>
</beans>
--------------------------------------------------------------------------------
Client.java
package cj.client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cj.domain.Hello;
public class Client {
public static void main(String[] args) {
String[] paths = { "/cj/client/clientContext.xml" };
ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);
Hello hello=(Hello) ctx.getBean("helloService");;
System.out.println(hello.hello("frank"));
}
}
--------------------------------------------------------------------------------
C# Client:
using System;
using hessiancsharp.client;
using System.Reflection;
....
...
..
.
static void Main(string[] args)
{
CHessianProxyFactory chpf=new CHessianProxyFactory();
Hello hello=(Hello) chpf.Create(Type.GetType("C3JavaC3Client.Hello"),"http://localhost:8080/C3Java/hello.do");
System.Console.Out.WriteLine("Call Hello:" +hello.hello("中文"));
}