Hessian的使用介绍
2018-12-17 本文已影响1人
凯睿看世界
原文:
https://blog.csdn.net/flysun3344/article/details/52929481
一:添加hessian-4.0.7.jar至工程中
image.png二:服务端发布的服务代码
建立web工程
1.接口Isay
package fly.sun.demo1;
public interface Isay {
public String sayHello(String arg1,String arg2);
}
2.接口的实现类IsayImpl
package fly.sun.demo1;
public class IsayImpl implements Isay {
public String sayHello(String arg1, String arg2) {
return "Hello:" + arg1 + arg2;
}
}
3.在web.xml中配置Hessian的Servlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>hello</servlet-name>
<!-- 配置Hessian的Servlet(来源于jar包) -->
<servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
<init-param>
<!-- 固定写为service-class -->
<param-name>service-class</param-name>
<param-value>fly.sun.demo1.IsayImpl</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
tomcat中启动工程即已经将服务发布了。
三:客户端调用服务端发布的服务
<pre style="box-sizing: border-box; outline: 0px; padding: 8px; margin: 0px 0px 24px; position: relative; white-space: pre-wrap; word-wrap: break-word; overflow-x: auto; font-family: Consolas, Inconsolata, Courier, monospace; font-size: 14px; line-height: 22px; color: rgb(0, 0, 0);">客户端也需要导入</pre>
hessian-4.0.7.jar
客户端代码如下:
import com.caucho.hessian.client.HessianProxyFactory;
public class HelloTest {
public static void main(String[] args) throws Exception {
// Hessian代理工厂
HessianProxyFactory factory = new HessianProxyFactory();
// 访问配置的Servlet路径
String url = "http://localhost:8080/发布服务的工程名/hello";
// 使用Hessian工厂获得接口的具体实现类
Isay i = (Isay)factory.create(Isay.class, url);
System.out.println(i.sayHello("fly", "sun"));
}
}
运行结果:
image.png