1)引入jar包
com.caucho hessian 4.0.51
2)创建服务接口
1 import java.io.File; 2 import java.util.List; 3 4 public interface HelloSessian { 5 6 String sayHello(String name); 7 8 ListgetExams(); 9 10 File download(String path);11 12 String upload(File file);13 }
3)写实现类,其中对象要实现序列化接口,因为hessian传递的是二进制流
1 import java.io.File; 2 import java.util.ArrayList; 3 import java.util.Date; 4 import java.util.List; 5 6 public class HelloSessianImpl implements HelloSessian { 7 8 @Override 9 public String sayHello(String name) {10 return "Hello " + name;11 }12 13 @Override14 public ListgetExams() {15 List exams = new ArrayList<>();16 Exam e1 = new Exam();17 e1.setId(1001);18 e1.setName("yyq");19 e1.setStart(new Date());20 Exam e2 = new Exam();21 e2.setId(1002);22 e2.setName("lucy");23 e2.setStart(new Date());24 exams.add(e1);25 exams.add(e2);26 return exams;27 }28 29 @Override30 public File download(String path) {31 return new File(path);32 }33 34 @Override35 public String upload(File file) {36 String name = file.getName();37 return "Upload " + name + " ok!";38 }39 40 }
1 import java.io.Serializable; 2 import java.util.Date; 3 4 public class Exam implements Serializable { 5 /**serialVersionUID:(用一句话描述这个变量表示什么). 6 */ 7 private static final long serialVersionUID = 1L; 8 9 private int id;10 private String name;11 private Date start;12 13 public int getId() {14 return id;15 }16 17 public void setId(int id) {18 this.id = id;19 }20 21 public String getName() {22 return name;23 }24 25 public void setName(String name) {26 this.name = name;27 }28 29 public Date getStart() {30 return start;31 }32 33 public void setStart(Date start) {34 this.start = start;35 }36 37 @Override38 public String toString() {39 return "Exam [id=" + id + ", name=" + name + ", start=" + start + "]";40 }41 }
4)配置servlet
12 13hessian 3com.caucho.hessian.server.HessianServlet 45 8home-api 6henu.yyq.hessian.HelloSessian 79 12home-class 10henu.yyq.hessian.HelloSessianImpl 1114 hessian 15/hessian 16
5)部署并且启动tomcat,不解释
6)客户端调用
客户端引入jar包,记得版本要一致
写调用测试类
1 public static void main(String[] args) throws IOException { 2 3 HessianProxyFactory factory = new HessianProxyFactory(); 4 factory.setOverloadEnabled(true); 5 HelloSessian proxy = (HelloSessian) factory.create(HelloSessian.class, "http://localhost:8080/hessian"); 6 String ret = proxy.sayHello("test"); 7 System.out.println(ret); 8 Listexams = proxy.getExams(); 9 for (Exam exam : exams) {10 System.out.println(exam.toString());11 }12 13 File download = proxy.download("d:/1.txt");14 System.out.println(download.getName());15 FileInputStream in = new FileInputStream(download);16 byte[] buf = new byte[1024];17 in.read(buf);18 System.out.println(new String(buf));19 in.close();20 21 // proxy.upload(file)22 }
结果:
Hello testExam [id=1001, name=yyq, start=Tue May 01 23:48:14 CST 2018]Exam [id=1002, name=lucy, start=Tue May 01 23:48:14 CST 2018]1.txt哈哈哈第二行