使用CXF生成webservice


1.使用cxf生成webservice,引入cxf jar包,在pom.xml中添加依賴即可:

<!--CXF--!>
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-bundle</artifactId> </dependency>

2.定義一個webservice服務的客戶端:

com.abc.webservice
import
javax.jws.WebMethod; import javax.jws.WebResult; import javax.jws.WebService; /** * 畢業生認證webservice服務的客戶端 * * @author * */ @WebService(targetNamespace = "http://www.abc.com") public interface BysRzServerService { /** * 查詢畢業生信息(畢業生認證) * * @param xm * 姓名 * @param byzh * 畢業生號 * @return RspBean */ @WebMethod(operationName = "bysRz") @WebResult(name = "result") public String bysRz(String xm,String byzh) throws Exception; }

注:WebMethod(operationName="bysRz")即為webservice的方法名,WebResult(name="result")表示webservice返回值

@WebService(endpointInterface="com.abc.webservice.BysRzServerService")
public class BysRzServerServiceImpl implements BysRzServerService {
    private static final Log log = LogFactory.getLog(BysRzServerServiceImpl.class);
    
    /**
     * 畢結業綜合查詢service
     */
    @Override
    public String bysRz(String xm, String byzh) throws Exception {
        //進行業務邏輯處理,將處理結果返回
        StringBuffer sb=new StringBuffer("");
        return sb.toString();
    }
    
}

3.在spring-webservice.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 ">  
    <!--認證webservice -->
  <jaxws:server id="bysRzServerService" serviceClass="com.abc.webservice.BysRzServerService"
            address="/bysRzServerService" >
            <jaxws:serviceBean>
                <bean class="com.abc.webservice.BysRzServerServiceImpl">
                    <property name="bysZhcxService" ref="bysZhcxService"/><!--該處為業務邏輯處理需要使用的bean對象-->
                </bean>
        <!--webservice攔截器,可以對調用webservice的客戶端進行驗證-->
        
<jaxws:inInterceptors>

          <bean class="com.cattsoft.baseplatform.func.sm.web.WebserviceAuthenticationInterceptor">
            <property name="sysParamCacheManager" ref="sysParamCacheManager"/>
          </bean>
        </jaxws:inInterceptors>

            </jaxws:serviceBean>        
    </jaxws:server>

  //另一種配置方法

  <jaxws:endpoint id="bysRzServerService"

    implementorClass="com.abc.webservice.BysRzServerService"

    address="/bysRzServerService">

    <jaxws:implementor>
      <bean  class="
com.abc.webservice.BysRzServerServiceImpl">

        <property name="imDealDeptUserService" ref="imDealDeptUserService" />
      </bean>
    </jaxws:implementor>
  </jaxws:endpoint>

</beans>

4.將spring-webservice.xml文件引入到applicationContext.xml中,在web.xml中配置CXF的servlet配置:

  

<!-- CXF -->
    <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>/webservice/*</url-pattern>
    </servlet-mapping>

5.通過ip可以測試webservice是否成功:http://localhost:8088/項目名稱/webservice/bysRzServerService?wsdl

6.通過AXIS調用webservice

//service所在的URL
        String endpoint= "http://localhost:8088/zhongzhi/webservice/ideaUserServerService";
        //加入調用webservice用戶驗證信息
        String namespace="";//命名空間
        SOAPHeaderElement header = new SOAPHeaderElement(namespace,"Authentication");
        header.setPrefix("");
        header.addChildElement("username").addTextNode("admin");
        header.addChildElement("password").addTextNode("admin");
        //創建一個服務(service)調用(call)
        Service service =new Service();
        Call call = (Call)service.createCall();//通過service創建call對象
        call.addHeader(header);
        //設置service所在URL
        call.setTargetEndpointAddress(new URL(endpoint));
        //設置命名空間,webservice方法名稱
        call.setOperationName(new QName("http://www.cattsoft.com","synchronizeIdeaUser"));
        //設置參數
        call.addParameter("userJson", XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter("sysDeptJson", XMLType.XSD_STRING, ParameterMode.IN);
        call.setReturnType(XMLType.XSD_STRING);
        //將兩個實體類轉換為json字符串進行傳遞
        String userJson = JSONObject.fromObject(ideaUser).toString();
        String sysDeptJson = JSONObject.fromObject(sysDept).toString();
        call.setUseSOAPAction(true);
        //調用webservice方法,傳遞參數,多個參數以數組形式傳遞
        String result = (String)call.invoke(new Object[]{userJson,sysDeptJson});
        Log.debug("國網同步省網數據結果:"+result);

7.對應的webservice服務端加入攔截器,進行調用webservice服務的驗證

package com.cattsoft.baseplatform.func.sm.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.xml.soap.SOAPException;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.w3c.dom.Node;

import com.cattsoft.baseplatform.cache.SysParamCacheManager;
import com.cattsoft.zhongzhi.core.utils.Constants;
import com.tongtech.backport.java.util.Arrays;

public class WebserviceAuthenticationInterceptor extends AbstractPhaseInterceptor<SoapMessage>{
    private SysParamCacheManager sysParamCacheManager;
    public WebserviceAuthenticationInterceptor() {
        super(Phase.PRE_INVOKE);
    }

    @Override
    public void handleMessage(SoapMessage msg) throws Fault {
        HttpServletRequest request=(HttpServletRequest)msg.get( AbstractHTTPDestination.HTTP_REQUEST);
        String url =request.getRequestURL().toString();
        String ip = url.substring(url.indexOf("/")+2,url.lastIndexOf(":"));
        //獲取數據庫配置的允許訪問的IP地址
        String ips= sysParamCacheManager.getEnableParamValue(Constants.ServerInfo.WEBSERVICE_ALLOWED_IP);
        List<String> list = Arrays.asList(ips.split(","));
        if(!list.contains(ip)){
            System.out.println("webservice調用異常-----未經授權的IP調用");
            throw new Fault(new SOAPException("未經授權的IP調用webservice"));
        }
    }


    public SysParamCacheManager getSysParamCacheManager() {
        return sysParamCacheManager;
    }

    public void setSysParamCacheManager(SysParamCacheManager sysParamCacheManager) {
        this.sysParamCacheManager = sysParamCacheManager;
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM