springboot整合CXF

1、添加依賴

<dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
        <version>3.2.4</version>
</dependency>

2又憨、創(chuàng)建實體類

package com.huaxun.springboot.entity;

import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID = -3628469724795296287L;
    private  int id;
    private String userName;
    private String passWord;
    private String userSex;
    private String nickName;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

}

3翠霍、創(chuàng)建service接口

package com.huaxun.springboot.service;

import com.huaxun.springboot.entity.User;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService
public interface UserService {
    @WebMethod//標注該方法為webservice暴露的方法,用于向外公布,它修飾的方法是webservice方法蠢莺,去掉也沒影響的寒匙,類似一個注釋信息。
    public User getUser(@WebParam(name = "userId") String userId);

    @WebMethod
    @WebResult(name="String",targetNamespace="")
    public String getUserName(@WebParam(name = "userId") String userId);
}

4躏将、創(chuàng)建接口實現(xiàn)類

package com.huaxun.springboot.service;

import com.huaxun.springboot.entity.User;
import org.springframework.stereotype.Component;


import javax.jws.WebService;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@WebService(serviceName="userService",//對外發(fā)布的服務名
        targetNamespace="http://service.demo.example.com",//指定你想要的名稱空間锄弱,通常使用使用包名反轉(zhuǎn)
        endpointInterface="com.huaxun.springboot.service.UserService")
@Component
public class UserServiceImpl implements UserService{

    private Map<String, User> userMap = new HashMap<String, User>();
    public UserServiceImpl() {
        System.out.println("向?qū)嶓w類插入數(shù)據(jù)");
        User user = new User();
        user.setId(111);
        user.setUserName("test1");

        userMap.put(user.getId()+"", user);

        user = new User();
        user.setId(112);
        user.setUserName("test2");
        userMap.put(user.getId()+"", user);

        user = new User();
        user.setId(113);
        user.setUserName("test3");
        userMap.put(user.getId()+"", user);
    }
    @Override
    public String getUserName(String userId) {
        return "userId為:" +userMap.get( userId).getUserName();
    }
    @Override
    public User getUser(String userId) {
        System.out.println("userMap是:"+userMap);
        return userMap.get(userId);
    }

}

5、創(chuàng)建CXF配置類

package com.huaxun.springboot.controller;

import com.huaxun.springboot.service.UserService;
import org.apache.cxf.Bus;

import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.ws.Endpoint;


@Configuration
public class CxfConfig {
    @Autowired
    private Bus bus;

    @Autowired
    UserService userService;

    /**
     * 此方法作用是改變項目中服務名的前綴名祸憋,此處127.0.0.1或者localhost不能訪問時会宪,請使用ipconfig查看本機ip來訪問
     * 此方法被注釋后:wsdl訪問地址為http://127.0.0.1:8080/services/user?wsdl
     * 去掉注釋后:wsdl訪問地址為:http://127.0.0.1:8080/soap/user?wsdl
     * @return
     */
    @SuppressWarnings("all")
    @Bean
    public ServletRegistrationBean dispatcherServlet() {
        return new ServletRegistrationBean(new CXFServlet(), "/soap/*");
    }

    /** JAX-WS
     * 站點服務
     * **/
    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(bus, userService);
        endpoint.publish("/user");
        return endpoint;
    }
}

6、運行springboot主程序

package com.huaxun.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

7蚯窥、頁面訪問服務

image.png

如上圖服務部署成功

8狈谊、編寫測試類

第二個測試用到了httpClient,引入相關(guān)依賴

<dependency>              
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

測試類代碼

package com.huaxun.springboot;

import com.huaxun.springboot.service.UserService;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


import org.apache.http.HttpEntity;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

public class Test {


    public static void main(String[] args) {
        Test.main1();
        Test.main2();
    }

    /**
     * 1.代理類工廠的方式,需要拿到對方的接口地址
     */
    public static void main1() {
        try {
            // 接口地址
            String address = "http://127.0.0.1:8080/soap/user?wsdl";
            // 代理工廠
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
            // 設置代理地址
            jaxWsProxyFactoryBean.setAddress(address);
            // 設置接口類型
            jaxWsProxyFactoryBean.setServiceClass(UserService.class);
            // 創(chuàng)建一個代理接口實現(xiàn)
            UserService us = (UserService) jaxWsProxyFactoryBean.create();
            // 數(shù)據(jù)準備
            String userId = "111";
            // 調(diào)用代理接口的方法調(diào)用并返回結(jié)果
            String result = us.getUserName(userId);
            System.out.println("返回結(jié)果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 2:httpClient調(diào)用
     */
    public static void main2() {
        try {

            final String SERVER_URL = "http://127.0.0.1:8080/soap/user"; // 定義需要獲取的內(nèi)容來源地址

            HttpPost request = new HttpPost(SERVER_URL);
            String soapRequestData = getRequestXml();
            HttpEntity re = new StringEntity(soapRequestData, HTTP.UTF_8);
            request.setHeader("Content-Type","application/soap+xml; charset=utf-8");

            request.setEntity(re);

            HttpResponse httpResponse = new DefaultHttpClient().execute(request);


            if (httpResponse.getStatusLine().getStatusCode() ==200) {
                String xmlString = EntityUtils.toString(httpResponse.getEntity());
                String jsonString = parseXMLSTRING(xmlString);


                System.out.println("---"+jsonString);

            }


        } catch (Exception e) {


            e.printStackTrace();

        }

    }

    public static String parseXMLSTRING(String xmlString) {
        String returnJson = "";
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
            Element root = doc.getDocumentElement();//根節(jié)點
            Node node = root.getFirstChild();
            while (!node.getNodeName().equals("String")) {
                node = node.getFirstChild();
            }
            if (node.getFirstChild() != null) returnJson = node.getFirstChild().getNodeValue();
            System.out.println("獲取的返回參數(shù)為:" + returnJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnJson;
    }

    private static String getRequestXml(){
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\"?>");
        sb.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
        sb.append(" xmlns:sam=\"http://service.springboot.huaxun.com/\" ");  //前綴,這一串由服務端提供
        sb.append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"");
        sb.append(" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
        sb.append("<soap:Header/>");
        sb.append("<soap:Body>");
        sb.append("<sam:getUserName>");  //“getUserName”調(diào)用方法名
        sb.append("<userId>111</userId>"); //傳參,“userId”是配置在服務端的參數(shù)名稱,“111”是要傳入的參數(shù)值
        sb.append("</sam:getUserName>");
        sb.append("</soap:Body>");
        sb.append("</soap:Envelope>");
        return sb.toString();
    }


}

運行main1()方法結(jié)果如下

image.png

運行main2()方法結(jié)果如下

image.png

至此整合完成

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末沟沙,一起剝皮案震驚了整個濱河市河劝,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌矛紫,老刑警劉巖赎瞎,帶你破解...
    沈念sama閱讀 221,198評論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異颊咬,居然都是意外死亡务甥,警方通過查閱死者的電腦和手機牡辽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評論 3 398
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來敞临,“玉大人态辛,你說我怎么就攤上這事⊥δ颍” “怎么了奏黑?”我有些...
    開封第一講書人閱讀 167,643評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長编矾。 經(jīng)常有香客問我熟史,道長,這世上最難降的妖魔是什么窄俏? 我笑而不...
    開封第一講書人閱讀 59,495評論 1 296
  • 正文 為了忘掉前任蹂匹,我火速辦了婚禮,結(jié)果婚禮上凹蜈,老公的妹妹穿的比我還像新娘限寞。我一直安慰自己,他們只是感情好仰坦,可當我...
    茶點故事閱讀 68,502評論 6 397
  • 文/花漫 我一把揭開白布昆烁。 她就那樣靜靜地躺著,像睡著了一般缎岗。 火紅的嫁衣襯著肌膚如雪静尼。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,156評論 1 308
  • 那天传泊,我揣著相機與錄音鼠渺,去河邊找鬼。 笑死眷细,一個胖子當著我的面吹牛拦盹,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播溪椎,決...
    沈念sama閱讀 40,743評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼普舆,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了校读?” 一聲冷哼從身側(cè)響起沼侣,我...
    開封第一講書人閱讀 39,659評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎歉秫,沒想到半個月后蛾洛,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,200評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,282評論 3 340
  • 正文 我和宋清朗相戀三年轧膘,在試婚紗的時候發(fā)現(xiàn)自己被綠了钞螟。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,424評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡谎碍,死狀恐怖鳞滨,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蟆淀,我是刑警寧澤拯啦,帶...
    沈念sama閱讀 36,107評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站扳碍,受9級特大地震影響提岔,放射性物質(zhì)發(fā)生泄漏仙蛉。R本人自食惡果不足惜笋敞,卻給世界環(huán)境...
    茶點故事閱讀 41,789評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望荠瘪。 院中可真熱鬧夯巷,春花似錦、人聲如沸哀墓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽篮绰。三九已至后雷,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間吠各,已是汗流浹背臀突。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留贾漏,地道東北人候学。 一個月前我還...
    沈念sama閱讀 48,798評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像纵散,于是被迫代替她去往敵國和親梳码。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,435評論 2 359

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理伍掀,服務發(fā)現(xiàn)掰茶,斷路器,智...
    卡卡羅2017閱讀 134,693評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,264評論 25 707
  • 今天我21歲了蜜笤,按理說過生日通常都是或興奮或精彩符匾。可是今天的感覺兩個字可以形容――平淡瘩例。 也許是知道自己長大了...
    時自分閱讀 561評論 2 2
  • 在某些時刻啊胶,在那命運的節(jié)點甸各,它總是會以那非凡的答案去告訴我們,那冥冥中注定焰坪,又或是早已書寫好結(jié)局的故事趣倾,不論我...
    為明天奮斗的木又寸閱讀 570評論 0 4
  • 明知需要去找工作找工作找工作卻沒有一點動力
    小丸子與安德烈閱讀 146評論 0 0