浅谈Spring2.5集合Web Service

开发 后端
本文将简单谈谈Spring2.5集合Web Service。Spring为JAX-RPC servlet的端点实现提供了一个方便的基类 - ServletEndpointSupport. 未来暴露我们的 AccountService我们扩展Spring的ServletEndpointSupport类并在这里实现了我们的业务逻辑,通常将调用交给业务层。

使用JAX-RPC暴露基于servlet的web服务

Spring为JAX-RPC servlet的端点实现提供了一个方便的基类 - ServletEndpointSupport. 未来暴露我们的 AccountService我们扩展Spring的ServletEndpointSupport类并在这里实现了我们的业务逻辑,通常将调用交给业务层。

  1. /**  
  2. * JAX-RPC compliant RemoteAccountService implementation that simply delegates  
  3. * to the AccountService implementation in the root web application context.  
  4. *  
  5. * This wrapper class is necessary because JAX-RPC requires working with dedicated  
  6. * endpoint classes. If an existing service needs to be exported, a wrapper that  
  7. * extends ServletEndpointSupport for simple application context access is  
  8. * the simplest JAX-RPC compliant way.  
  9. *  
  10. * This is the class registered with the server-side JAX-RPC implementation.  
  11. * In the case of Axis, this happens in "server-config.wsdd" respectively via  
  12. * deployment calls. The web service engine manages the lifecycle of instances  
  13. * of this class: A Spring application context can just be accessed here.  
  14. */import org.springframework.remoting.jaxrpc.ServletEndpointSupport;  
  15.  
  16. public class AccountServiceEndpoint extends ServletEndpointSupport implements RemoteAccountService {  
  17.       
  18.     private AccountService biz;  
  19.  
  20.     protected void onInit() {  
  21.         this.biz = (AccountService) getWebApplicationContext().getBean("accountService");  
  22.     }  
  23.  
  24.     public void insertAccount(Account acc) throws RemoteException {  
  25.         biz.insertAccount(acc);  
  26.     }  
  27.  
  28.     public Account[] getAccounts(String name) throws RemoteException {  
  29.         return biz.getAccounts(name);  
  30.     }  

AccountServletEndpoint需要在Spring中同一个上下文的web应用里运行,以获得对Spring的访问能力。如果使用Axis,把AxisServlet定义复制到你的'web.xml'中,并且在'server-config.wsdd'中设置端点(或使用发布工具)。参看JPetStore这个例子中OrderService是如何用Axis发布成一个Web服务的。

使用JAX-RPC访问web服务

Spring提供了两个工厂bean用来创建Web服务代理,LocalJaxRpcServiceFactoryBean 和 JaxRpcPortProxyFactoryBean。前者只返回一个JAX-RPC服务类供我们使用。后者是一个全功能的版本,可以返回一个实现我们业务服务接口的代理。本例中,我们使用后者来为前面段落中暴露的AccountService端点创建一个代理。你将看到Spring对Web服务提供了极好的支持,只需要很少的代码 - 大多数都是通过类似下面的Spring配置文件:

  1. <bean id="accountWebService" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean"> 
  2.     <property name="serviceInterface" value="example.RemoteAccountService"/> 
  3.     <property name="wsdlDocumentUrl" value="http://localhost:8080/account/services/accountService?WSDL"/> 
  4.     <property name="namespaceUri" value="http://localhost:8080/account/services/accountService"/> 
  5.     <property name="serviceName" value="AccountService"/> 
  6.     <property name="portName" value="AccountPort"/> 
  7. </bean> 

serviceInterface是我们客户端将使用的远程业务接口。 wsdlDocumentUrl是WSDL文件的URL. Spring需要用它作为启动点来创建JAX-RPC服务。 namespaceUri对应.wsdl文件中的targetNamespace。 serviceName 对应.wsdl文件中的服务名。 portName 对应.wsdl文件中的端口号。

现在我们可以很方便的访问web服务,因为我们有一个可以将它暴露为RemoteAccountService接口的bean工厂。我们可以在Spring中这样使用:

  1. <bean id="client" class="example.AccountClientImpl"> 
  2.     ...  
  3.     <property name="service" ref="accountWebService"/> 
  4. </bean> 

从客户端代码上看,除了它抛出RemoteException,我们可以把这个web服务当成一个普通的类进行访,。

  1. public class AccountClientImpl {  
  2.  
  3.     private RemoteAccountService service;  
  4.       
  5.     public void setService(RemoteAccountService service) {  
  6.         this.service = service;  
  7.     }  
  8.       
  9.     public void foo() {  
  10.         try {  
  11.             service.insertAccount(...);  
  12.         }  
  13.         catch (RemoteException ex) {  
  14.             // ouch  
  15.         }  
  16.     }  

我们可以不检查受控异常RemoteException,因为Spring将它自动转换成相应的非受控异常RemoteException。这也需要我们提供一个非RMI的接口。现在配置文件如下:

  1. <bean id="accountWebService" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean"> 
  2.     <property name="serviceInterface" value="example.AccountService"/> 
  3.     <property name="portInterface" value="example.RemoteAccountService"/> 
  4. </bean> 

我们的serviceInterface变成了非RMI接口。我们的RMI接口现在使用portInterface属性来定义。我们的客户端代码可以避免处理异常java.rmi.RemoteException:

  1. public class AccountClientImpl {  
  2.  
  3.     private AccountService service;  
  4.       
  5.     public void setService(AccountService service) {  
  6.         this.service = service;  
  7.     }  
  8.       
  9.     public void foo() {  
  10.         service.insertAccount(...);  
  11.     }  

请注意你也可以去掉"portInterface"部分并指定一个普通业务接口作为"serviceInterface"。这样JaxRpcPortProxyFactoryBean将自动切换到JAX-RPC "动态调用接口", 不使用固定端口存根来进行动态调用。这样做的好处是你甚至不需要使用一个RMI相关的Java接口(比如在非Java的目标web服务中);你只需要一个匹配的业务接口。查看JaxRpcPortProxyFactoryBean的javadoc来了解运行时实行的细节。

注册JAX-RPC Bean映射

T为了传递类似Account等复杂对象,我们必须在客户端注册bean映射。

注意

在服务器端通常在'server-config.wsdd'中使用Axis进行bean映射注册。

我们将使用Axis在客户端注册bean映射。为此,我们需要通过程序注册这个bean映射:

  1. public class AxisPortProxyFactoryBean extends JaxRpcPortProxyFactoryBean {  
  2.  
  3.     protected void postProcessJaxRpcService(Service service) {  
  4.         TypeMappingRegistry registry = service.getTypeMappingRegistry();  
  5.         TypeMapping mapping = registry.createTypeMapping();  
  6.         registerBeanMapping(mapping, Account.class, "Account");  
  7.         registry.register("http://schemas.xmlsoap.org/soap/encoding/", mapping);  
  8.     }  
  9.  
  10.     protected void registerBeanMapping(TypeMapping mapping, Class type, String name) {  
  11.         QName qName = new QName("http://localhost:8080/account/services/accountService", name);  
  12.         mapping.register(type, qName,  
  13.                 new BeanSerializerFactory(type, qName),  
  14.                 new BeanDeserializerFactory(type, qName));  
  15.     }  

注册自己的JAX-RPC 处理器

本节中,我们将注册自己的javax.rpc.xml.handler.Handler 到Web服务代理,这样我们可以在SOAP消息被发送前执行定制的代码。Handler是一个回调接口。jaxrpc.jar中有个方便的基类javax.rpc.xml.handler.GenericHandler供我们继承使用:

  1. public class AccountHandler extends GenericHandler {  
  2.  
  3.     public QName[] getHeaders() {  
  4.         return null;  
  5.     }  
  6.  
  7.     public boolean handleRequest(MessageContext context) {  
  8.         SOAPMessageContext smc = (SOAPMessageContext) context;  
  9.         SOAPMessage msg = smc.getMessage();  
  10.         try {  
  11.             SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();  
  12.             SOAPHeader header = envelope.getHeader();  
  13.             ...  
  14.         }  
  15.         catch (SOAPException ex) {  
  16.             throw new JAXRPCException(ex);  
  17.         }  
  18.         return true;  
  19.     }  

我们现在要做的就是把AccountHandler注册到JAX-RPC服务,这样它可以在消息被发送前调用 handleRequest(..)。Spring目前对注册处理方法还不提供声明式支持,所以我们必须使用编程方式。但是Spring中这很容易实现,我们只需覆写专门为此设计的 postProcessJaxRpcService(..) 方法:

  1. public class AccountHandlerJaxRpcPortProxyFactoryBean extends JaxRpcPortProxyFactoryBean {  
  2.  
  3.     protected void postProcessJaxRpcService(Service service) {  
  4.         QName port = new QName(this.getNamespaceUri(), this.getPortName());  
  5.         List list = service.getHandlerRegistry().getHandlerChain(port);  
  6.         list.add(new HandlerInfo(AccountHandler.class, null, null));  
  7.         logger.info("Registered JAX-RPC AccountHandler on port " + port);  
  8.     }  

***,我们要记得更改Spring配置文件来使用我们的工厂bean:

  1. <bean id="accountWebService" class="example.AccountHandlerJaxRpcPortProxyFactoryBean"> 
  2.     ...  
  3. </bean> 

使用JAX-WS暴露基于servlet的web服务
Spring为JAX-WS servlet端点实现提供了一个方便的基类 - SpringBeanAutowiringSupport。要暴露我们的AccountService接口,我们可以扩展Spring的SpringBeanAutowiringSupport类并实现我们的业务逻辑,通常把调用交给业务层。我们将简单的使用Spring 2.5的@Autowired注解来声明依赖于Spring管理的bean。

  1. /**  
  2. * JAX-WS compliant AccountService implementation that simply delegates  
  3. * to the AccountService implementation in the root web application context.  
  4. *  
  5. * This wrapper class is necessary because JAX-WS requires working with dedicated  
  6. * endpoint classes. If an existing service needs to be exported, a wrapper that  
  7. * extends SpringBeanAutowiringSupport for simple Spring bean autowiring (through  
  8. * the @Autowired annotation) is the simplest JAX-WS compliant way.  
  9. *  
  10. * This is the class registered with the server-side JAX-WS implementation.  
  11. * In the case of a Java EE 5 server, this would simply be defined as a servlet  
  12. * in web.xml, with the server detecting that this is a JAX-WS endpoint and reacting  
  13. * accordingly. The servlet name usually needs to match the specified WS service name.  
  14. *  
  15. * The web service engine manages the lifecycle of instances of this class.  
  16. * Spring bean references will just be wired in here.  
  17. */import org.springframework.web.context.support.SpringBeanAutowiringSupport;  
  18.  
  19. @WebService(serviceName="AccountService")  
  20. public class AccountServiceEndpoint extends SpringBeanAutowiringSupport {  
  21.  
  22.     @Autowired  
  23.     private AccountService biz;  
  24.  
  25.     @WebMethod  
  26.     public void insertAccount(Account acc) {  
  27.        biz.insertAccount(acc);  
  28.     }  
  29.  
  30.     @WebMethod  
  31.     public Account[] getAccounts(String name) {  
  32.        return biz.getAccounts(name);  
  33.     }  

为了能够让Spring上下文使用Spring设施,我们的AccountServletEndpoint类需要运行在同一个web应用中。在Java EE 5环境中这是默认的情况,它使用JAX-WS servlet端点安装标准契约。详情请参阅Java EE 5 web服务教程。

使用JAX-WS暴露单独web服务
Sun JDK 1.6提供的内置JAX-WS provider 使用内置的HTTP服务器来暴露web服务。Spring的SimpleJaxWsServiceExporter类检测所有在Spring应用上下文中配置的l@WebService 注解bean,然后通过默认的JAX-WS服务器(JDK 1.6 HTTP服务器)来暴露它们。

在这种场景下,端点实例将被作为Spring bean来定义和管理。它们将使用JAX-WS来注册,但其生命周期将一直跟随Spring应用上下文。这意味着Spring的显示依赖注入可用于端点实例。当然通过@Autowired来进行注解驱动的注入也可以正常工作。

  1. <bean class="org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter"> 
  2.     <property name="baseAddress" value="http://localhost:9999/"/> 
  3. </bean> 
  4.  
  5. <bean id="accountServiceEndpoint" class="example.AccountServiceEndpoint"> 
  6.     ...  
  7. </bean> 
  8.  
  9. ... 

AccountServiceEndpoint类可能源自Spring的 SpringBeanAutowiringSupport类,也可能不是。因为这里的端点是由Spring完全管理的bean。这意味着端点实现可能像下面这样没有任何父类定义 - 而且Spring的@Autowired配置注解仍然能够使用:

  1. @WebService(serviceName="AccountService")  
  2. public class AccountServiceEndpoint {  
  3.  
  4.     @Autowired  
  5.     private AccountService biz;  
  6.  
  7.     @WebMethod  
  8.     public void insertAccount(Account acc) {  
  9.        biz.insertAccount(acc);  
  10.     }  
  11.  
  12.     @WebMethod  
  13.     public Account[] getAccounts(String name) {  
  14.        return biz.getAccounts(name);  
  15.     }  

使用Spring支持的JAX-WS RI来暴露服务

Sun的JAX-WS RI被作为GlassFish项目的一部分来开发,它使用了Spring支持来作为JAX-WS Commons项目的一部分。这允许把JAX-WS端点作为Spring管理的bean来定义。这与前面章节讨论的单独模式类似 - 但这次是在Servlet环境中。注意这在Java EE 5环境中是不可迁移的,建议在没有EE的web应用环境如Tomcat中嵌入JAX-WS RI。

与标准的暴露基于servlet的端点方式不同之处在于端点实例的生命周期将被Spring管理。这里在web.xml将只有一个JAX-WS servlet定义。在标准的Java EE 5风格中(如上所示),你将对每个服务端点定义一个servlet,每个服务端点都代理到Spring bean (通过使用@Autowired,如上所示)。

关于安装和使用详情请查阅https://jax-ws-commons.dev.java.net/spring/

使用JAX-WS访问web服务
类似JAX-RPC支持,Spring提供了2个工厂bean来创建JAX-WS web服务代理,它们是LocalJaxWsServiceFactoryBean和JaxWsPortProxyFactoryBean。前一个只能返回一个JAX-WS服务对象来让我们使用。后面的是可以返回我们业务服务接口的代理实现的完整版本。这个例子中我们使用后者来为AccountService端点再创建一个代理:

  1. <bean id="accountWebService" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean"> 
  2.     <property name="serviceInterface" value="example.AccountService"/> 
  3.     <property name="wsdlDocumentUrl" value="http://localhost:8080/account/services/accountService?WSDL"/> 
  4.     <property name="namespaceUri" value="http://localhost:8080/account/services/accountService"/> 
  5.     <property name="serviceName" value="AccountService"/> 
  6.     <property name="portName" value="AccountPort"/> 
  7. </bean> 

serviceInterface是我们客户端将使用的远程业务接口。 wsdlDocumentUrl是WSDL文件的URL. Spring需要用它作为启动点来创建JAX-RPC服务。 namespaceUri对应.wsdl文件中的targetNamespace。 serviceName 对应.wsdl文件中的服务名。 portName 对应.wsdl文件中的端口号。

现在我们可以很方便的访问web服务,因为我们有一个可以将它暴露为AccountService接口的bean工厂。我们可以在Spring中这样使用:

  1. <bean id="client" class="example.AccountClientImpl"> 
  2.     ...  
  3.     <property name="service" ref="accountWebService"/> 
  4. </bean> 

从客户端代码上我们可以把这个web服务当成一个普通的类进行访问:

  1. public class AccountClientImpl {  
  2.  
  3.     private AccountService service;  
  4.  
  5.     public void setService(AccountService service) {  
  6.         this.service = service;  
  7.     }  
  8.  
  9.     public void foo() {  
  10.         service.insertAccount(...);  
  11.     }  

注意: 上面被稍微简化了,因为JAX-WS需要端点接口及实现类来使用@WebService, @SOAPBinding等注解。 这意味着你不能简单的使用普通的Java接口和实现来作为JAX-WS端点,你需要首先对它们进行相应的注解。这些需求详情请查阅JAX-WS文档。

使用XFire来暴露Web服务

XFire是一个Codehaus提供的轻量级SOAP库。暴露XFire是通过XFire自带的context,这个context将和RemoteExporter风格的bean相结合,后者需要被加入到在你的WebApplicationContext中。对于所有让你来暴露服务的方法,你需要创建一个DispatcherServlet类并有相应的WebApplicationContext来封装你将要暴露的服务:

  1. <servlet> 
  2.     <servlet-name>xfire</servlet-name> 
  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
  4. </servlet> 

你还必须链接XFire配置。这是通过增加一个context文件到由ContextLoaderListener(或者ContextLoaderServlet)加载的 contextConfigLocations 参数中。

  1. <context-param> 
  2.     <param-name>contextConfigLocation</param-name> 
  3.     <param-value>classpath:org/codehaus/xfire/spring/xfire.xml</param-value> 
  4. </context-param> 
  5.  
  6. <listener> 
  7.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  8. </listener> 

在你加入一个Servlet映射后(映射/*到上面定义的XFire Servlet),你只需要增加一个额外的bean来使用XFire暴露服务。例如,在 'xfire-servlet.xml' 中增加如下配置:

  1. <beans> 
  2.  
  3.     <bean name="/Echo" class="org.codehaus.xfire.spring.remoting.XFireExporter"> 
  4.         <property name="serviceInterface" value="org.codehaus.xfire.spring.Echo"/> 
  5.         <property name="serviceBean"> 
  6.             <bean class="org.codehaus.xfire.spring.EchoImpl"/> 
  7.         </property> 
  8.         <!-- the XFire bean is defined in the xfire.xml file --> 
  9.         <property name="xfire" ref="xfire"/> 
  10. </bean> 
  11.  
  12. </beans> 

XFire处理了其他的事情。它检查你的服务接口并产生一个WSDL文件。这里的部分文档来自XFire网站,要了解更多有关XFire Spring的集成请访问 docs.codehaus.org/display/XFIRE/Spring。

【编辑推荐】

  1. JSF和Spring的集成
  2. 在Spring中进行集成测试
  3. 比较JSF、Spring MVC、Stripes、Struts 2、Tapestry、Wicket
  4. Spring中的TopLink ServerSession
  5. Spring is coming
责任编辑:彭凡 来源: 百度空间
相关推荐

2009-06-24 09:22:04

Spring2.5新特

2009-06-25 13:23:50

Spring2.5

2009-06-18 13:44:05

Spring2.0spring2.5

2009-10-13 11:22:46

VB.NET调用Web

2009-06-18 09:42:52

SpringXFire构建Web

2009-06-29 15:51:48

Spring容器

2009-06-01 12:04:38

JPASpringJAVA

2009-09-11 11:25:35

LINQ函数集合

2009-06-26 17:34:29

Spring入门

2017-06-06 10:30:12

前端Web宽度自适应

2009-08-18 09:06:41

C#对象和集合

2010-04-14 15:09:49

Oracle函数

2009-12-08 17:48:28

Web Service

2009-08-20 15:38:50

C#建立Web Ser

2009-09-14 14:01:21

LINQ泛型数据集

2011-09-08 17:48:33

Web Widget

2009-07-06 10:25:14

Java Web Se

2011-08-12 11:36:07

2012-04-19 09:34:21

ibmdw

2009-08-11 13:27:22

C#创建Web Ser
点赞
收藏

51CTO技术栈公众号