SpringMVC集成Hessian

首先强调这里是SpringMVC,不是Spring,这两者在集成Hessian的时候还是有差别的。Spring集成相对简单,网上随便​​搜一个​​就行。

SpringMVC有点麻烦。

注:如果你还不了解Hessian,可以看​​Hessian简单示例​

前提条件

假设你的SpringMVC环境已经配置了好了。

主要是在web.xml中有了如下的配置:

<servlet>
<!-- 名字随便,和你springmvc的配置xml一致即可 -->
<servlet-name>sys</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!-- 你自己的映射配置 -->
</servlet-mapping>

另外你已经配置了相应的​​sys-servlet.xml​​​文件(​​sys​​名字和你自己的保持一致即可)。

集成Hessian

为了针对Hessian的请求,在​​web.xml​​中增加了如下映射:

<servlet-mapping>
<!-- 名字要保持一致 -->
<servlet-name>sys</servlet-name>
<url-pattern>*.hessian</url-pattern>
</servlet-mapping>

然后在​​sys-servlet.xml​​中添加如下配置:

<!--hessian-->
<bean id="httpRequestHandlerAdapter" class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean id="importService" class="com.xxx.pr.service.impl.ImportServiceImpl"/>
<bean name="/import.hessian" class="org.springframework.remoting.caucho.HessianServiceExporter">
<property name="service" ref="importService"/>
<property name="serviceInterface" value="com.xxx.pr.service.ImportService"/>
</bean>

​HessianServiceExporter​​​是继承​​HttpRequestHandler​​​接口的,所以需要​​HttpRequestHandlerAdapter​​来处理这种请求。

​BeanNameUrlHandlerMapping​​​的作用是,当​​<bean>​​​的​​name​​​属性以​​/​​开头的时候,映射为url请求。

​HessianServiceExporter​​​中的两项属性,一个是​​service​​​,​​ref​​​属性指向的实现类。一个是​​serviceInterface​​,指向的是接口。

做好如上配置后,启动服务器。

然后访问​http://localhost:8080/myweb/import.hessian​即可。具体地址根据自己的来写。

在浏览器打开后,会显示下面的样子:

HTTP Status 405 - HessianServiceExporter only supports POST requests

type Status report

message HessianServiceExporter only supports POST requests

description The specified HTTP method is not allowed for the requested resource.

Apache Tomcat/7.0.56

如果如上显示,说明就没有问题了。

调用

如果在Spring中调用,可以尝试如下配置

<bean id="importBean"   
class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<property name="serviceUrl"
value="http://localhost:8080/myweb/import.hessian"></property>
<property name="serviceInterface" value="com.xxx.pr.service.ImportService"></property>
</bean>

也可以直接使用Hessian调用

String url = "http://localhost:8080/myweb/import.hessian";
HessianProxyFactory factory = new HessianProxyFactory();
ImportService basic = (ImportService) factory.create(ImportService.class, url);