天天看點

SpringMVC內建Hessian

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.

調用

如果在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);