Web Service的CXF实现(Spring整合方式)

jopen 11年前

 新建Java Web项目,采用maven管理jar包,本文章只是提供核心代码文件如下:

(1)maven的pom.xml

(2)cxf-base.xml

(3)cxf-bz-client.xml 客户端配置

(4)cxf-bz-server.xml服务端配置

(5)WSOrderService 业务接口定义

(6)WSOrderServiceImpl 业务接口实现

(7)BZClientHandler,BZServiceHandler 用户认证拦截

(8)web.xml 项目web配置

(9)demo.properties url和用户配置信息

备注:其中涉及spring相关配置文件未列出。

 

1) 主要核心pom.xml配置如下:

   <!-- spring framework -->    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-aop</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-asm</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-beans</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-context</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-core</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-expression</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-jdbc</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-orm</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-tx</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-web</artifactId>     <version>${spring.version}</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-context-support</artifactId>     <version>${spring.version}</version>    </dependency>     <!--end of spring framework -->        <!-- CXF Dependencies -->    <dependency>     <groupId>org.apache.cxf</groupId>     <artifactId>cxf-rt-frontend-jaxws</artifactId>     <version>${cxf.version}</version>    </dependency>    <dependency>      <groupId>org.apache.cxf</groupId>      <artifactId>cxf-rt-transports-common</artifactId>      <version>2.5.4</version>      <type>jar</type>      <scope>compile</scope>    </dependency>    <dependency>      <groupId>org.apache.cxf</groupId>      <artifactId>cxf-rt-core</artifactId>      <version>${cxf.version}</version>      <type>jar</type>      <scope>compile</scope>    </dependency>    <dependency>      <groupId>org.apache.cxf</groupId>      <artifactId>cxf-rt-transports-http-jetty</artifactId>      <version>${cxf.version}</version>      <type>jar</type>      <scope>compile</scope>    </dependency>    <!-- End of CXF Dependencies -->

(2)cxf-base.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"       xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"       xsi:schemaLocation="             http://www.springframework.org/schema/beans              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd             http://cxf.apache.org/jaxws              http://cxf.apache.org/schemas/jaxws.xsd          http://cxf.apache.org/transports/http/configuration          http://cxf.apache.org/schemas/configuration/http-conf.xsd">               <http-conf:conduit name="*/.*">    <http-conf:client AllowChunking="false" />   </http-conf:conduit>        <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" />      <!-- 对接web service配置 -->      <import resource="classpath:conf/cxf/cxf-bz-server.xml" />      <import resource="classpath:conf/cxf/cxf-bz-client.xml" />  </beans>

(3)cxf-bz-client.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:aop="http://www.springframework.org/schema/aop"   xmlns:tx="http://www.springframework.org/schema/tx"   xmlns:context="http://www.springframework.org/schema/context"   xmlns:jaxws="http://cxf.apache.org/jaxws"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd             http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"   default-lazy-init="true">   <!--    -->   <bean id="bzClientSoapHandler" class="com.lshop.ws.util.BZClientHandler">        <property name="accountNum" value="${bz.ws.account}"></property>       <property name="password" value="${bz.ws.password}"></property>      </bean>      <!-- -->   <jaxws:client id="bzExpressService" name="bzExpressService" serviceClass="com.lshop.ws.web.bz.order.BzExpressService" wsdlLocation="${bz.sys.url}/ws/WSOrderService?wsdl">    <jaxws:handlers>     <ref bean="bzClientSoapHandler" />    </jaxws:handlers>       </jaxws:client>  </beans>

(4)cxf-bz-server.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:aop="http://www.springframework.org/schema/aop"   xmlns:tx="http://www.springframework.org/schema/tx"   xmlns:context="http://www.springframework.org/schema/context"   xmlns:jaxws="http://cxf.apache.org/jaxws"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd             http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"   default-lazy-init="true">  <!--       -->   <bean id="bzServerSoapHandler" class="com.lshop.ws.util.BZServiceHandler">       <property name="accountNum" value="${bz.ws.account}"></property>       <property name="password" value="${bz.ws.password}"></property>      </bean>      <jaxws:server  serviceClass="com.lshop.ws.server.bz.order.service.WSOrderService" address="/WSOrderService">       <jaxws:handlers>        <ref bean="bzServerSoapHandler" />       </jaxws:handlers>            <jaxws:serviceBean>        <ref bean="WSOrderService" />       </jaxws:serviceBean>      </jaxws:server>     </beans>

 

(5)WSOrderService定义业务接口

package com.lshop.ws.server.bz.order.service;  import java.util.Date;  import javax.jws.WebParam;  import javax.jws.WebService;  import javax.jws.soap.SOAPBinding;  import javax.jws.soap.SOAPBinding.Style;  import com.lshop.ws.server.bz.order.bean.LvOrderDtoResposne;    @WebService(name = "WSOrderService")  @SOAPBinding(style=Style.RPC)  public interface WSOrderService  {   /**    * 同步已经审核的订单到商务接口定义    * @Method: synAuditOrderToBZ     * @Description:      * @param startTime  审核开始时间    * @param endTime    审核结算时间    * @return OrderList    */   public LvOrderDtoResposne synAuditOrderToBZ(     @WebParam(name = "startTime") String startTime,     @WebParam(name = "endTime") String endTime);     }

(6)WSOrderServiceImpl业务实现类

package com.lshop.ws.server.bz.order.service;  import java.util.ArrayList;  import java.util.Date;  import java.util.HashMap;  import java.util.List;  import java.util.Map;  import javax.annotation.Resource;  import javax.jws.WebService;  import org.apache.commons.logging.Log;  import org.apache.commons.logging.LogFactory;  import org.springframework.stereotype.Service;  import com.gv.core.hibernate3.HibernateBaseDAO;  import com.gv.core.service.impl.BaseServiceImpl;  import com.gv.core.util.ObjectUtils;  import com.lshop.common.pojo.logic.LvOrderDetails;  import com.lshop.common.pojo.logic.LvOrderPackageDetails;  import com.lshop.common.util.DateUtils;  import com.lshop.ws.server.bz.order.bean.LvOrderDto;  import com.lshop.ws.server.bz.order.bean.LvOrderDtoResposne;  import com.lshop.ws.server.bz.order.bean.LvProductDto;  import com.lshop.ws.server.bz.order.bean.Result;    @Service("WSOrderService")  @WebService(endpointInterface = "com.lshop.ws.server.bz.order.service.WSOrderService")  public class WSOrderServiceImpl extends BaseServiceImpl implements WSOrderService {   @Resource   private HibernateBaseDAO dao;      private static final Log logger = LogFactory.getLog(WSOrderServiceImpl.class);      /**    * 同步已经审核的订单到商务接口定义    * @Method: synAuditOrderToBZ     * @Description:      * @param startTime  审核开始时间(查询范围起始时间,格式:yyyy-mm-dd HH:mm:ss)    * @param endTime    审核结束时间(查询范围结束时间,格式:yyyy-mm-dd HH:mm:ss)    * @return OrderList    */   @Override   public LvOrderDtoResposne synAuditOrderToBZ(String startTime, String endTime) {    if(logger.isInfoEnabled()){       logger.info("*****WSOrderServiceImpl.synAuditOrderToBZ() method begin*****");    }        LvOrderDtoResposne lvOrderDtoResposne=new LvOrderDtoResposne();    List<LvOrderDto> orderList=new ArrayList<LvOrderDto>();    //判断查询日期时间差        //根据审核时间查询已经审核订单集合    try {     if(ObjectUtils.isNotEmpty(startTime)&&ObjectUtils.isNotEmpty(endTime)){      String hql=" select DISTINCT ls.ord as ord from  LvOrderLogs ls,LvOrder o " +        " where ls.ord=o.oid " +        " and o.isServiceAudit=1 " +        " and o.isFinanceAudit=1 " +        " and o.isdelete=0 " +        " and ls.createTime>=:startTime and ls.createTime <=:endTime ";      Map param=new HashMap();      param.put("startTime", DateUtils.convertToDateTime(startTime));      param.put("endTime", DateUtils.convertToDateTime(endTime));      List listTmp = dao.getMapListByHql(hql, param).getList();      if(ObjectUtils.isNotEmpty(listTmp)){       for (int i = 0; i < listTmp.size(); i++) {        Map map=(Map) listTmp.get(i);        //查询订单信息        LvOrderDto lvOrderDto=this.getOrderInfo(String.valueOf(map.get("ord")));           orderList.add(lvOrderDto);       }      }     }     lvOrderDtoResposne.setOrderList(orderList);     lvOrderDtoResposne.getResult().setStatus(Result.STATUS_SUCCEED);     lvOrderDtoResposne.getResult().setMessage("成功");    } catch (Exception e) {     lvOrderDtoResposne.getResult().setStatus(Result.STATUS_FAIL);     lvOrderDtoResposne.getResult().setMessage(e.getMessage());     e.printStackTrace();    }        if(logger.isInfoEnabled()){     logger.info("*****WSOrderServiceImpl.synAuditOrderToBZ() method end*****");    }    return lvOrderDtoResposne;   }         /**    *     * @Method: getOrderDetailsByOid     * @Description: 根据订单号查询订单详情及对应的产品信息    * @param oid  订单号    * @return List<LvProductDto>    */   protected List<LvProductDto> getOrderDetailsByOid(String oid){        return null;   }      /**    *     * @Method: getOrderInfo     * @Description: 根据订单号查询订单    * @param oid  订单号    * @return List<LvProductDto>    */   protected LvOrderDto getOrderInfo(String oid){        return null;   }  }

(7)BZClientHandler,BZServiceHandler用户认证拦截。

package com.lshop.ws.util;  import java.io.IOException;  import java.util.Set;  import javax.xml.namespace.QName;  import javax.xml.soap.SOAPBody;  import javax.xml.soap.SOAPElement;  import javax.xml.soap.SOAPEnvelope;  import javax.xml.soap.SOAPException;  import javax.xml.soap.SOAPFault;  import javax.xml.soap.SOAPHeader;  import javax.xml.soap.SOAPMessage;  import javax.xml.ws.handler.MessageContext;  import javax.xml.ws.handler.soap.SOAPHandler;  import javax.xml.ws.handler.soap.SOAPMessageContext;  import javax.xml.ws.soap.SOAPFaultException;     public class BZClientHandler implements SOAPHandler<SOAPMessageContext> {      private String accountNum;   private String password;       public String getAccountNum() {    return accountNum;   }   public void setAccountNum(String accountNum) {    this.accountNum = accountNum;   }   public String getPassword() {    return password;   }   public void setPassword(String password) {    this.password = password;   }   @Override      public boolean handleMessage(SOAPMessageContext context) {        System.out.println("Server : handleMessage()......");            try{        SOAPMessage soapMsg = context.getMessage();        SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();           SOAPHeader soapHeader = soapEnv.getHeader();                   //if no header, add one        if (soapHeader == null){                soapHeader = soapEnv.addHeader();         }                     SOAPElement accountNumNode = soapHeader.addChildElement(new QName("http://service.webservice.datainterface.bz.gv.com/","accountNum"));        accountNumNode.setNodeValue("accountNum");        accountNumNode.setValue(accountNum);                SOAPElement passwordNode = soapHeader.addChildElement(new QName("http://service.webservice.datainterface.bz.gv.com/","password"));        passwordNode.setNodeValue("password");        passwordNode.setValue(password);             soapMsg.writeTo(System.out);        return true;         }catch(SOAPException e){      System.err.println(e);     }catch(IOException e){      System.err.println(e);     }              //continue other handler chain      return false;    }        @Override    public boolean handleFault(SOAPMessageContext context) {         System.out.println("Server : handleFault()......");         return true;    }        @Override    public void close(MessageContext context) {     System.out.println("Server : close()......");    }        @Override    public Set<QName> getHeaders() {     System.out.println("Server : getHeaders()......");     return null;    }            private void generateSOAPErrMessage(SOAPMessage msg, String reason) {          try {             SOAPBody soapBody = msg.getSOAPPart().getEnvelope().getBody();             SOAPFault soapFault = soapBody.addFault();             soapFault.setFaultString(reason);             throw new SOAPFaultException(soapFault);           }          catch(SOAPException e) { }       }  }

(8)web.xml配置web servcie请求拦截url.

 <!--备注:只是保留关键配置,省略了其他配置信息-->   <!-- web service config  begin-->   <servlet>            <servlet-name>cxf</servlet-name>            <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>            <load-on-startup>1</load-on-startup>        </servlet>        <servlet-mapping>            <servlet-name>cxf</servlet-name>            <url-pattern>/ws/*</url-pattern>        </servlet-mapping>     <!-- web service config  end-->

(9)demo.properties

bz.sys.url=http\://127.0.0.1\:8080  bz.ws.account=demo  bz.ws.password=demo400

 

配置完成可以通过下面的服务端url访问

http://127.0.0.1:8080/ws/WSOrderService?wsdl

客户端先生成客户端java文件,在调用接口实现即可。