Fork me on GitHub
基于CXF Java 搭建Web Service

基于CXF Java 搭建Web Service (Restful Web Service与基于SOAP的Web Service混合方案)

快十年没玩SSH这类东西了,由于上个产品用Restful Service 作为应用服务接口,所以顺手整理一下。考虑到当年我刚入门时经历的一些痛苦,所以这里我会讲得详细些,共享之。

一,选择一个合适的,Web开发环境:

   我选择的是Eclipse for J2EE,当然大家可以选择MyEclipse我只是嫌最新版的MyEclipse Crack太烦,所以没用它。当年我也是最喜欢它的哟。如果你手头只有Eclipse for Java没关系,安装一个WTP就可以了。

   a.首先创建一个Dynamic Web Project :

 

     在创建的第一页,Project Name 我用的是"MyServices"中要在Target Runtime中选择一个容器服务器,我这里测试环境下,选择的是Tomcat ,如果没有,可以在右边点击“New Runtime"进行新增Tomcat 运行环境。

     在Project创建的最后一页最好选中创建一个web.xml省得你去创建,缺省情况下,这个web.xml只配置了欢迎页面。如index.php等。

  b.测试一下,是否这个环境可以发布Build后的代码及网页到Tomcat测试环境中运行:

     在左边的"Web Content"目录下的”WEB-INF"子目录,创建一个index.jsp文件进行测试。创建完成后,重新build项目,然后在右下方的Server Tab里会自动列出你刚才选择的Tomcat发布环境。你点击这个Tomcat Server

    我的环境是Tomcat Server 7.0 然后右键菜单中选择“Publish" 你会看到 服务器,及服务器下面你的项目右边会由”Republish"变成“Synchronized" ,说明工程编译结果都已成功发布到Tomcat Server测试环境下了。

    点击Tomcat Server 7.0 选择”Start" 服务启动,你就可以在你的网页里输入“http://localhost:8080/MyServices/index.jsp"你就可以看到你的网页内容了。

   因为这个网站插图不方便,有时间再插一些图示吧。

 

二,关于cxf 框架的运行时序的个人思考过程:

     0.Tomcat启动时,加载web.xml,根据web.xml的配置,把CXF 的Servlet 放到Tomcat的侦听端口的映射中,同时也把Spring的Bean加载器也加载到Tomcat的进程空间中,Spring根据初始化的配置文件(比如beans.xml),加载Bean对象。在加载过程中,会根据配置文件中的beans.xml中的xmlns进行分析,调用对应的加载器进行解释加载,这里调用cxf的加载器进行加载。cxf加载器会根据 beans.xml中对应的项加载最终实现的class文件,这些class在对应的java源文件编译过程中,根据java文件中的annomation标记符进行处理,使得这些class加载时形成正确的path 与对象的映射。

     1.客户端发出请求,通过XML/HTTP把请求及参数对象转为XML经过HTTP传到Servlet容器中。

     2.CXF会根据Path与对象的映射找到正确的对象,如果是Restful Web Service还会再根据映射找到Path中对应的执行方法。

三,创建一个基于CXF及Spring的SOAP Web Service:

     1.创建Web Service 相关的类:

       因为这种类型Web Service是SOA(面象服务架构)的,所以是提供一个远程的RPC接口。所以首先要有一个接口,当然,在服务端要提供真正的服务,所以要有一个这个接口在服务端的实现。下面分别实现:

 IHelloWorld.java:  

package com.services.soap;

import javax.jws.WebParam;

import javax.jws.WebService;

@WebService 

public interface IHelloWorld {

        public String speakoutUserInfo(@WebParam(name = "param") ParamDTO obj);

}

HelloWorld.java:

package com.services.soap;

import javax.jws.WebService;

/**  *   * 使用@WebService指向Interface定义类即可.  */ 

@WebService(endpointInterface = "com.services.soap.IHelloWorld") 

public class HelloWorld implements IHelloWorld{

 @Override

 public String speakoutUserInfo(ParamDTO obj) {

  // TODO Auto-generated method stub

        return "hello";  

}

}

上述的服务实现用到一个对象,这个对象可以做为参数远程进行传递,一般叫做DTO(数据传输对象)。当然你可以不用对象,用普通的数据类型这个实例一次性都表现一下。

ParamDTO.java:

package com.services.soap;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlType;

/**  

* Web Service传输信息的DTO.  

* 分离entity类与web service接口间的耦合,隔绝entity类的修改对接口的影响. 使用JAXB 2.0的annotation标注JAVA-XML映射,尽量使用默认约定.  *   

*/ 

@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "User") 

public class ParamDTO  {

        protected Integer id;

        protected String name; 

         public Integer getId()      {

              return id;

        }

        public void setId(Integer value)      {

              id = value;

       }

        public String getName()      {

              return name;

      }

        public void setName(String value)      {

             name = value;

      } 

}

2.在配置文件中体映射这个Service:

我们定义这个Beans.xml

<?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:jaxws="http://cxf.apache.org/jaxws"  
    xsi:schemaLocation="  
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">    
    <jaxws:endpoint id="webServiceHelloWorld"  
        address="/HelloWorld" implementor="com.services.soap.HelloWorld"/>  
</beans> 

这个Beans.xml放到Spring的加载Beans的配置文件中被引用:

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
    <import resource="classpath*:META-INF/cxf/cxf.xml" />  
    <import resource="classpath*:META-INF/cxf/cxf-extension-soap.xml" />  
    <import resource="classpath*:META-INF/cxf/cxf-servlet.xml" />  
    <import resource="classpath:beans.xml" />  //注意这行代码的引用
    
</beans> 

当然我们要在Web.xml中配置Spring:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>webrest</display-name>
  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>WEB-INF/classes/applicationContext.xml</param-value>  
    </context-param>  
    <listener>  
        <listener-class>  
            org.springframework.web.context.ContextLoaderListener  
        </listener-class>  
    </listener>  
    <servlet>  
        <servlet-name>CXFServlet</servlet-name>  
        <servlet-class>  
            org.apache.cxf.transport.servlet.CXFServlet  
        </servlet-class>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>CXFServlet</servlet-name>  
        <url-pattern>/*</url-pattern>  
    </servlet-mapping>  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

四,创建一个基于CXF及Spring的Restful Web Service:

  这个就相对简单了。因为经不需要直接接供RPC接口给客户端,只是其于ROA的方式提供资源的操作,可以理解为基于一些xml,json的表达一些资源对象变态变化的传输同步给远程服务。

  所以通过xml映射对象,Annomation进行直接映射方法与path.所以直接写实现类就行了,当然cxf还有别的框架有其它的映射或配置方式。

 a.代码实现:

  先上代码:

 HelloWorld.java

package com.services.rest;

 import javax.ws.rs.Consumes;

 import javax.ws.rs.GET;

 import javax.ws.rs.POST;

 import javax.ws.rs.Path;

 import javax.ws.rs.PathParam;

 import javax.ws.rs.Produces;

 import javax.ws.rs.core.Response;

 import org.codehaus.jackson.jaxrs.JacksonJsonProvider;  

 @Path("/hello")

 public class HelloWorld {

     @GET

     @Path("/echo/{input}")

     @Produces("text/plain")

     public String ping(@PathParam("input") String input) {

         return input + ":in server!";

     }

     @POST

     @Produces("application/json")

     @Consumes("application/json")

     @Path("/jsonBean")

     public Response modifyJson(JsonBean input) {

            input.setCommand(222);

            input.getParam().put("content", "welcome to server!");

           return Response.ok().entity(input).build();

     }

}

其中用到JsonBean对象这个是可以远程传送参数对象,一般情况无需特别的定义。就可以直接用了。我这里定义如下:

JsonBean:

package com.services.rest;

import java.util.Map;

public class JsonBean {

 private Integer command;

 private Integer protocolVersion;

 private String  platformType;

 private Map<String, Object> param;

 public Integer getCommand() {

    return command;

 }

 public void setCommand(Integer command) {

     this.command = command;

 }

 public Integer getProtocolVersion() {

     return protocolVersion;

 }

 public void setProtocolVersion(Integer protocolVersion) {

     this.protocolVersion = protocolVersion;

 }

 public String getPlatformType() {

     return platformType;

 }

 public void setPlatformType(String platformType) {

    this.platformType = platformType;

 }

 public Map<String, Object> getParam() {

     return param;

 }

 public void setParam(Map<String, Object> param) {

     this.param = param;

 }

 }

 b.进行发布:

配置一个rest-services.xml进行映射:

<?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:jaxrs="http://cxf.apache.org/jaxrs"   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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">

  <import resource="classpath:META-INF/cxf/cxf.xml" />

  <context:property-placeholder/>   <context:annotation-config/>   <bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer"/>   <bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"/>

   <jaxrs:server id="services" address="/">     <jaxrs:serviceBeans>       <bean class="com.services.rest.HelloWorld" />     </jaxrs:serviceBeans>     <jaxrs:providers>         <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>     </jaxrs:providers>     </jaxrs:server>

</beans>

在Spring的加载配置文件(applicationContext.xml)里引入:

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
    <import resource="classpath*:META-INF/cxf/cxf.xml" />  
    <import resource="classpath*:META-INF/cxf/cxf-extension-soap.xml" />  
    <import resource="classpath*:META-INF/cxf/cxf-servlet.xml" />  
    <import resource="classpath:rest-services.xml" /> 
</beans>

OK,大功告成。

到时此我们能把这两种模式的Web Service同时在一个框架里发布吗?当然可以:)要做的只有一步,就是在上面的applicationContext.xml里同时加载两个Service的映射文件就可以了。

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
    <import resource="classpath*:META-INF/cxf/cxf.xml" />  
    <import resource="classpath*:META-INF/cxf/cxf-extension-soap.xml" />  
    <import resource="classpath*:META-INF/cxf/cxf-servlet.xml" /> 

    <import resource="classpath:beans.xml" /> 
    <import resource="classpath:rest-services.xml" /> 
</beans>

现在就你就可以编译完成,Publish到你的tomcat上进行测试了,不过一定要注意,在发布选项里一定要把你项目工程中引用的jar依赖库(比如,cxf相关,spring相关的,Json相关的)同时发布到你的Tomcat Server的运行环境里,这里只需要修改:项目(MyServices)右键=》Properties=>Deployment Assembly=>Add=>Java Build Path Entries 不过在引入的jar过多时可能会造成冲突,假如在测试时,说CXF 的一个Discoveryxxx对象..... Null Point之类的错误:

SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
'bookservice': Invocation of init method failed; nested exception is org.apache.cxf.service.factory.ServiceConstructionException
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:
1422)
        .......

        Caused by: org.apache.cxf.service.factory.ServiceConstructionException
        at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:
201)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      
        ...

 Caused by: java.lang.NullPointerException
        at org.apache.cxf.ws.discovery.listeners.WSDiscoveryServerListener.startServer(WSDiscoveryServerListener.java:
64)
        at org.apache.cxf.bus.managers.ServerLifeCycleManagerImpl.startServer(ServerLifeCycleManagerImpl.java:
61)
        at org.apache.cxf.endpoint.ServerImpl.start(ServerImpl.java:
146)
        at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:
192)
          ........

就是最常见的cxf-services-ws-discovery-service-2.x.x.jar冲突,去掉这个.jar的依赖即可。

到这里应该完成了。

下面就可以用各种客户端或者浏览器进行测试了:

1.Native 客户端测试:

a.cxf的WebClient:

b.Spring RestTemplate:

2.浏览器测试:

a.

b.

 

---未完,这两天再加上去一些手机整合方案---

 

 

 
 
posted on 2013-03-04 14:38  HackerVirus  阅读(292)  评论(0编辑  收藏  举报