创建一个web项目hessianServer,导入 hessian-4.0.62.jar
创建 Customer 实现 Serializable 接口
import java.io.Serializable;
public class Customer implements Serializable {
private String id;
private String name;
private String address;
...
}
创建 CustomerServiceImpl
package com.gwl.crm.service.impl;
import com.gwl.crm.model.Customer;
import com.gwl.crm.service.CustomerService;
import java.util.ArrayList;
import java.util.List;
public class CustomerServiceImpl implements CustomerService {
@Override
public List<Customer> findAll() {
Customer c1 = new Customer("01","zhangsan","beijing");
Customer c2 = new Customer("02","lisi","shenzhen");
List<Customer> customers = new ArrayList<>();
customers.add(c1);
customers.add(c2);
return customers;
}
}
配置 web.xml
<servlet>
<servlet-name>hessian</servlet-name>
<servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
<init-param>
<param-name>home-class</param-name>
<param-value>com.gwl.crm.service.impl.CustomerServiceImpl</param-value>
</init-param>
<init-param>
<param-name>home-api</param-name>
<param-value>com.gwl.crm.service.CustomerService</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>hessian</servlet-name>
<url-pattern>/hessian/customer</url-pattern>
</servlet-mapping>
创建一个客户端项目,导入 hessian-4.0.62.jar,复制web项目hessianServer 中的 Customer 和 CustomerService到客户端项目中
import com.caucho.hessian.client.HessianProxyFactory;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
HessianProxyFactory factory = new HessianProxyFactory();
CustomerService customerService = (CustomerService) factory.create(CustomerService.class,"http://localhost:8080/hessianServer_war_exploded/hessian/customer");
List<Customer> customers = customerService.findAll();
// 输出 [{address=beijing, name=zhangsan, id=01}, {address=shenzhen, name=lisi, id=02}]
System.out.println(customers);
}
}