spring整合Hessian

xiaoxiao2021-02-28  21

  上篇文章简单的介绍了Hessian以及它的一些执行原理,现在我们来看看它与强大框架spring的集成吧!

一、服务端使用spring,我们得下载Hessian支持包和Spring的相应的jar包,可以在我的资源库中进行免费下载:

http://download.csdn.net/detail/harderxin/7129231

1、新建web工程,我取名为HessianSpringServer,在web/WEB-INFO/BIN中导入我们相应的jar包,跟上篇文章一样,编写我们的实体类和接口类、以及接口实现类:

实体用户类,因为该类要通过网络层传输,所以必须实现Serializable接口:

[java]  view plain  copy package com.server.bean;    import java.io.Serializable;    public class User implements Serializable{            /**      *       */      private static final long serialVersionUID = 7175134832651443717L;      //用户编号      private int id;      //用户名      private String userName;      //密码      private String password;        public int getId() {          return id;      }        public void setId(int id) {          this.id = id;      }        public String getUserName() {          return userName;      }        public void setUserName(String userName) {          this.userName = userName;      }        public String getPassword() {          return password;      }        public void setPassword(String password) {          this.password = password;      }            public User(int id, String userName, String password) {          super();          this.id = id;          this.userName = userName;          this.password = password;      }        @Override      public int hashCode() {          final int prime = 31;          int result = 1;          result = prime * result + id;          result = prime * result                  + ((password == null) ? 0 : password.hashCode());          result = prime * result                  + ((userName == null) ? 0 : userName.hashCode());          return result;      }        @Override      public boolean equals(Object obj) {          if (this == obj)              return true;          if (obj == null)              return false;          if (getClass() != obj.getClass())              return false;          User other = (User) obj;          if (id != other.id)              return false;          if (password == null) {              if (other.password != null)                  return false;          } else if (!password.equals(other.password))              return false;          if (userName == null) {              if (other.userName != null)                  return false;          } else if (!userName.equals(other.userName))              return false;          return true;      }  }  

定义我们的接口类:

[java]  view plain  copy package com.server.service;    import java.util.List;    import com.server.bean.User;    public interface UserService {            public List<User> getUser();        }  

定义我们的接口实现类:

[java]  view plain  copy package com.server.service.impl;    import java.util.ArrayList;  import java.util.List;    import com.server.bean.User;  import com.server.service.UserService;    public class UserServiceImpl implements UserService{        public List<User> getUser() {          //我们可以在这个方法中与数据库打交道          List<User> list=new ArrayList<User>();          list.add(new User(1,"Mary","123456"));          list.add(new User(2,"Jack","236547"));          list.add(new User(3,"Joy","362541"));          return list;      }  }  

2、新建spring配置文件springremoting-servlet.xml,让接口及实现类由spring容器去管理:

[html]  view plain  copy <?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="          http://www.springframework.org/schema/beans          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd          http://www.springframework.org/schema/context          http://www.springframework.org/schema/context/spring-context-3.0.xsd">                    <!-- Hessian服务接口Impl注入 -->          <bean id="userService" class="com.server.service.impl.UserServiceImpl"/>                    <!-- 使用HessianServiceExporter为服务接口Impl在网络地址中映射一个Hessian服务-->      <!-- 完整的远程调用请求<a href="http://localhost:8080/HessianSpringServer/sr/userService" target="_blank">Url:http://localhost:8080/HessianSpringServer/sr/userService</a>,前部分在web.xml中已经进行了配置 -->          <bean name="/userService" class="org.springframework.remoting.caucho.HessianServiceExporter">              <!-- Hessian服务的接口 -->              <property name="serviceInterface" value="com.server.service.UserService"/>              <!-- Hessian服务的接口Impl -->              <property name="service" ref="userService"></property>          </bean>  </beans>  

3、配置我们的web.xml文件,让服务器启动后能够加载到我们的springremoting-servlet.xml,以及配置访问路径

[html]  view plain  copy <?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">            <servlet>          <!-- 完整的远程调用请求Url:http://localhost:8080/HessianSpringServer/sr/* -->          <servlet-name>springremoting</servlet-name>          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>          <init-param>              <param-name>contextConfigLocation</param-name>              <!-- 服务启动加载 springremoting-servlet.xml-->              <param-value>classpath:springremoting-servlet.xml</param-value>          </init-param>          <load-on-startup>1</load-on-startup>      </servlet>      <servlet-mapping>          <servlet-name>springremoting</servlet-name>          <url-pattern>/sr/*</url-pattern>      </servlet-mapping>      <welcome-file-list>          <welcome-file>index.jsp</welcome-file>      </welcome-file-list>  </web-app>  

好了,我们的简单的服务端搭建完成了,记得把我们的接口类(UserService)和实体类(User)打成相应的jar包(也可以在客户端复制服务端接口类的代码,这样太繁琐了),因为我们的客户端需要访问到,这是Hessian里面定义的,No Why!

将我们的项目部署到Tomcat服务器上,启动Tomcat,如果报错了,说明你的配置没有配好哦,得自己仔细检查检查,如果不报错,说明我们的服务端搭建完成,下面来编写我们的客户端吧!

二、客户端不使用Spring,新建java项目,导入我们的Hessian支持包和在服务端打包的借口类jar包

编写我们的测试类,因为我把没有spring和有spring的客户端测试类写在了一起,好做个对比:

[java]  view plain  copy package com.client.test;      import java.util.List;    import com.caucho.hessian.client.HessianProxyFactory;  import com.server.bean.User;  import com.server.service.UserService;    public class UserServiceTest {      public static void main(String[] args) {          //不使用Spring服务器访问地址          //String url="http://localhost:8080/HessianServer/us";          //使用spring服务器访问的地址          String url="http://localhost:8080/HessianSpringServer/sr/userService";          //获得HessianProxyFactory实例          HessianProxyFactory factory=new HessianProxyFactory();          try {              //不使用Spring创建我们的接口对象              //UserService userService=(UserService)factory.create(url);              //使用Spring创建我们的接口对象              UserService userService=(UserService)factory.create(UserService.class,url);              //执行服务端方法              List<User> users=userService.getUser();              //遍历输出              for(User user:users){                  System.out.println("id="+user.getId()+",name="+user.getUserName()+",pwd="+user.getPassword());              }          } catch (Exception e) {              e.printStackTrace();          }      }  }  

其实我在做测试的时候还是有一个疑问的,就是我发现在服务端Hessian和spring整合后,客户端需要这样去调用:factory.create(UserService.class,url);需要指定相应接口的class,不能直接使用url地址传入:factory.create(url);这样会抛出一个异常:UndeclaredThrowableException,其实服务端在spring配置文件里面已经给接口类以及实现类进行了注入:

[html]  view plain  copy <!-- Hessian服务接口Impl注入 -->      <bean id="userService" class="com.server.service.impl.UserServiceImpl"/>            <!-- 使用HessianServiceExporter为服务接口Impl在网络地址中映射一个Hessian服务-->  t;!-- 完整的远程调用请求Url:http://localhost:8080/HessianSpringServer/sr/userService -->      <bean name="/userService" class="org.springframework.remoting.caucho.HessianServiceExporter">          <!-- Hessian服务的接口 -->          <property name="serviceInterface" value="com.server.service.UserService"/>          <!-- Hessian服务的接口Impl -->          <property name="service" ref="userService"></property>      </bean>  

并且,没生成一个Service,都会要重新写一个bean,所以这里我觉得直接使用地址factory.create(url);是可以访问的,跟没有使用spring时候在web.xml中配置一样,可是它不行,应该是spring里面给它做处理了吧,我们必须要factory.create(UserService.class,url);不然,里面会找不到相应的实体类吧!大家在写代码的时候注意下就是了!

运行main函数,得到的结果为:

id=1,name=Mary,pwd=123456id=2,name=Jack,pwd=236547id=3,name=Joy,pwd=362541

测试成功,哈哈...!

三、客户端使用Spring,我们的客户端也可以使用Spring,让factory.create(UserService.class,url);交给spring容器去处理,同样,需要导入我们的Hessian支持包和在服务端打包的借口类jar包,还需要我们的spring支持包,上面已经给出了相应的下载地址,如果你客户端需要使用JUnit进行测试,也需要junit的测试类包,我的那个包文件里面都已经包含了

1、既然我们在客户端使用了spring,当然得编写我们的配置文件,例如springremoting-client.xml,然后将我们的访问地址和接口类在里面进行注入:

[html]  view plain  copy <?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="          http://www.springframework.org/schema/beans          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd          http://www.springframework.org/schema/context          http://www.springframework.org/schema/context/spring-context-3.0.xsd">                    <bean id="userService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">              <!-- 注入我们的接口类 -->              <property name="serviceInterface" value="com.server.service.UserService"/>              <!-- 服务器访问地址 -->              <property name="serviceUrl" value="http://localhost:8080/HessianSpringServer/sr/userService"/>          </bean>  </beans>  

2、编写我们的测试函数:

[html]  view plain  copy package com.client.test;    import java.util.List;    import org.springframework.context.ApplicationContext;  import org.springframework.context.support.ClassPathXmlApplicationContext;    import com.server.bean.User;  import com.server.service.UserService;    public class UserServiceSpringTest {      public static void main(String[] args) {          //加载我们的Spring配置文件          ApplicationContext context=new ClassPathXmlApplicationContext("springremoting-client.xml");          //获取我们的接口类          UserService userService=(UserService)context.getBean("userService");          List<User> users=userService.getUser();          //遍历输出          for(User user:users){              System.out.println("id="+user.getId()+",name="+user.getUserName()+",pwd="+user.getPassword());          }      }  }  

测试输出:

id=1,name=Mary,pwd=123456id=2,name=Jack,pwd=236547id=3,name=Joy,pwd=362541两种情况的不同之处在于客户端里面的Hessian工厂对象交给spring容器去管理了,各有各的好处,大家可以根据实际情况进行选择!

使用junit测试我们的客户端:

[java]  view plain  copy /**  *  * Copyright: Copyright (c) 2012 Asiainfo-Linkage  *  * client@date:2014-3-28  * @ClassName: UserServiceTest.java  * @Description: 该类的功能描述  *  * @version: v1.0.0上午9:01:27eleven  * @author: elevenHessianSpringClient  *  * Modification History:  * Date  Author  Version Description  * ---------------------------------------------------------*  * 2014-3-28 eleven v1.0.0 新建  */  package client;      import javax.annotation.Resource;    import org.junit.Test;  import org.junit.runner.RunWith;  import org.springframework.test.context.ContextConfiguration;  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;    import service.UserServiceI;    /**  * @Title: UserServiceTest.java  * @Description: TODO(这里用一句话描述这个类的作用)  * @author eleven  * @date 2014-3-28 上午9:01:27  *  */  @RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration(locations = {"classpath:springremoting-client.xml"})  public class UserServiceTest {            private UserServiceI userService;            @Resource      public void setUserService(UserServiceI userService) {          this.userService = userService;      }        @Test      public void test() {          System.out.println(userService.queryUserList());      }    }  

好了,Hessian与Spring整合完成,希望大家一起交流学习,共同进步!Hessian与sping、struts、hibernate三大框架整合,大家可以去尝试一下哦!

转载请注明原文地址: https://www.6miu.com/read-2629587.html

最新回复(0)