两个工程:hessianServer (web 项目) 和 hessianClient(工程类型没有限制)
1.在 hessianServer 工程中:新建实体类(需要实现Serializable 接口)
package com.ztd.model; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 1L; private int id; private int age; private String name; public User(int id, int age, String name) { super(); this.id = id; this.age = age; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.ztd.hessian; import com.ztd.model.User; public interface SayHello { String sayHello(User user); }3.在 hessianServer 工程中:新建实现类:SayHelloImpl(需要继承 HessianServlet 类)
package com.ztd.hessian.impl; import com.caucho.hessian.server.HessianServlet; import com.ztd.hessian.SayHello; import com.ztd.model.User; public class SayHelloImpl extends HessianServlet implements SayHello { @Override public String sayHello(User user) { return "基本信息:ID " + user.getId() + " 年龄:" + user.getAge() + " 姓名:" + user.getName(); } }
5.新建测试类:TestHessian
package com.ztd.test; import java.net.MalformedURLException; import com.caucho.hessian.client.HessianProxyFactory; import com.ztd.hessian.UserDao; import com.ztd.model.User; public class TestHessian { public static String url = "http://127.0.0.1:8080/hello"; public static void main(String[] args){ HessianProxyFactory factory = new HessianProxyFactory(); try { UserDao userDao = (UserDao) factory.create(UserDao.class, url); User user =new User(1, 23, "dada"); System.out.println(userDao.sayHello(user)); } catch (MalformedURLException e) { e.printStackTrace(); } } }
<?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/j2ee" xmlns:web="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_2_5.xsd" version="2.5"> <!-- 这种配置方式在 hessian-3.0.1.jar 会报错:server must extend HessianServlet,这个时候就使用下面的配置方式 --> <!-- <servlet> --> <!-- <servlet-name>hello</servlet-name> --> <!-- <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class> --> <!-- <init-param> --> <!-- <param-name>home-api</param-name> --> <!-- <param-value>com.ztd.dao.UserDao</param-value> --> <!-- </init-param> --> <!-- <init-param> --> <!-- <param-name>home-class</param-name> --> <!-- <param-value>com.ztd.dao.impl.UserDaoImpl</param-value> --> <!-- </init-param> --> <!-- <load-on-startup>1</load-on-startup> --> <!-- </servlet> --> <!-- 如果上面的方式有问题的话就使用下面的配置方式 --> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.ztd.hessian.impl.SayHelloImpl</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>