·利用HessianProxyFactory调用远程接口。
一、服务端【TestHessainServices】
1、接口
package app.demo; public interface BasicAPI { public void setTest(String test); public String hello(); public User getUser(); }
package app.demo; public interface BasicAPI { public void setTest(String test); public String hello(); public User getUser(); }
package app.demo; /** * @author * @创建时间:205-4-15 * @作用: hessian服务端 * 发布在服务器上,为客户端提供接口*/ public class BasicService implements BasicAPI { private String params = "测试,成功!!!"; @Override public void setTest(String test) { params = test; System.out.println("set greeting success:"+params); } @Override public String hello() { return params; } @Override public User getUser() { return new User("小明", "123456"); } }
4、web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <display-name></display-name> <!-- hessain配置 --> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class> <init-param> <param-name>service-class</param-name> <param-value>app.demo.BasicService</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
二、客户端【TestHessianClient】
1、接口和服务端一样
2、实体类和服务端一样
3、services
package app.demo; import com.caucho.hessian.client.HessianProxyFactory; /** * @author * @创建时间:205-4-15 * @作用: hessian客户端 * 客户端调用服务端的接口*/ public class BasicClient { public static void main(String[] args) throws Exception { // http://localhost:8081/TestHessainServices/-------发布在tomcat服务器上-----hello服务端上的web.xml配置servlet名字 String url ="http://localhost:8081/TestHessainServices/hello"; HessianProxyFactory factory = new HessianProxyFactory(); BasicAPI basic = (BasicAPI) factory.create(BasicAPI.class, url); System.out.println("测试1:" + basic.hello()); System.out.println("测试2:" + basic.getUser().getUserName()); System.out.println("测试3:" + basic.getUser().getPassword()); basic.setTest("测试"); System.out.println("测试4:" + basic.hello()); } }