浅谈Spring2.5集合WebService

使用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. public class AccountServiceEndpoint extends ServletEndpointSupport implements RemoteAccountService {
  16.     
  17.     private AccountService biz;
  18.     protected void onInit() {
  19.         this.biz = (AccountService) getWebApplicationContext().getBean("accountService");
  20.     }
  21.     public void insertAccount(Account acc) throws RemoteException {
  22.         biz.insertAccount(acc);
  23.     }
  24.     public Account[] getAccounts(String name) throws RemoteException {
  25.         return biz.getAccounts(name);
  26.     }
  27. }

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

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

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

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

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

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

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

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

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

 
 
 
  1. public class AccountClientImpl {
  2.     private AccountService service;
  3.     
  4.     public void setService(AccountService service) {
  5.         this.service = service;
  6.     }
  7.     
  8.     public void foo() {
  9.         service.insertAccount(...);
  10.     }
  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.     protected void postProcessJaxRpcService(Service service) {
  3.         TypeMappingRegistry registry = service.getTypeMappingRegistry();
  4.         TypeMapping mapping = registry.createTypeMapping();
  5.         registerBeanMapping(mapping, Account.class, "Account");
  6.         registry.register("http://schemas.xmlsoap.org/soap/encoding/", mapping);
  7.     }
  8.     protected void registerBeanMapping(TypeMapping mapping, Class type, String name) {
  9.         QName qName = new QName("http://localhost:8080/account/services/accountService", name);
  10.         mapping.register(type, qName,
  11.                 new BeanSerializerFactory(type, qName),
  12.                 new BeanDeserializerFactory(type, qName));
  13.     }
  14. }

注册自己的JAX-RPC 处理器

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

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

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

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

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

 
 
 
  1.  id="accountWebService" class="example.AccountHandlerJaxRpcPortProxyFactoryBean">
  2.     ...

使用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. @WebService(serviceName="AccountService")
  19. public class AccountServiceEndpoint extends SpringBeanAutowiringSupport {
  20.     @Autowired
  21.     private AccountService biz;
  22.     @WebMethod
  23.     public void insertAccount(Account acc) {
  24.        biz.insertAccount(acc);
  25.     }
  26.     @WebMethod
  27.     public Account[] getAccounts(String name) {
  28.        return biz.getAccounts(name);
  29.     }
  30. }

为了能够让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.  class="org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter">
  2.      name="baseAddress" value="http://localhost:9999/"/>
  3.  id="accountServiceEndpoint" class="example.AccountServiceEndpoint">
  4.     ...
  5. ...

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

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

使用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,如上所示)。

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

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

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

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

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

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

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

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

使用XFire来暴露Web服务

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

 
 
 
  1.     xfire
  2.     org.springframework.web.servlet.DispatcherServlet

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

 
 
 
  1.     contextConfigLocation
  2.     classpath:org/codehaus/xfire/spring/xfire.xml
  3.     org.springframework.web.context.ContextLoaderListener

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

 
 
 
  1.      name="/Echo" class="org.codehaus.xfire.spring.remoting.XFireExporter">
  2.          name="serviceInterface" value="org.codehaus.xfire.spring.Echo"/>
  3.          name="serviceBean">
  4.              class="org.codehaus.xfire.spring.EchoImpl"/>
  5.         
  6.         
  7.          name="xfire" ref="xfire"/>

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

本文题目:浅谈Spring2.5集合WebService
网页网址:http://www.shufengxianlan.com/qtweb/news28/458978.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联