SpringBoot整合CXF,使用webService


1、SpringBoot整合CXF,使用webService

CXF,Apache CXF = Celtix + XFire,開始叫 Apache CeltiXfire,后來更名為 Apache CXF,繼承了 Celtix 和 XFire 兩大開源項目的精華,提供了對 JAX-WS 全面的支持,並且提供了多種 Binding 、DataBinding、Transport 以及各種 Format 的支持,並且可以根據實際項目的需要,采用代碼優先(Code First)或者 WSDL 優先(WSDL First)來輕松地實現 Web Services 的發布和使用。Apache CXF已經是一個正式的Apache頂級項目。

1、導包

1.1、確定SpringBoot版本,才能正確導入與之版本契合的CXF包

使用IDEA打開已有的項目,顯示如圖所示,打開左側Project面板;在project面板下找到如圖所示的External Libraries;

在External Libraries面板下中找到如圖所示的Spirng-boot:xx.xx.xxrelease,即是xx.xx.xx的版本。

或者

或者點擊界面右側的Maven Project按鈕;打開dependencies后,找到如圖所示的spring-boot-start,即可查看到版本。

1.2、正確引入pom.xml文件
<!--webService接口依賴-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.cxf</groupId>
	<artifactId>cxf-rt-frontend-jaxws</artifactId>
	<version>3.1.6</version>
</dependency>
<dependency>
	<groupId>org.apache.cxf</groupId>
	<artifactId>cxf-rt-transports-http</artifactId>
	<version>3.1.6</version>
</dependency>

2、創建實體類

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、創建Service接口

package com.alibaba.wms.service;

import com.alibaba.wms.model.User;
import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 * name 暴露服務名稱
 * targetNamespace 命名空間,一般是接口的包名反轉
 */
@WebService(
        name = "UserService",
        targetNamespace = "http://service.wms.alibaba.com"
)
public interface UserService {

    /**
     * @WebMethod 標注該方法為webservice暴露的方法,用於向外公布,它修飾的方法是webservice方法,去掉也沒影響的,類似一個注釋信息。
     * @param userId
     * @return
     */
    @WebMethod
    User getUser(String userId);

    @WebMethod
    String getUserName( String userId);
}

4、創建接口實現類

package com.alibaba.wms.service.impl;

import com.alibaba.wms.model.User;
import com.alibaba.wms.service.UserService;
import org.springframework.stereotype.Component;
import javax.jws.WebService;
import java.util.HashMap;
import java.util.Map;

/**
 * serviceName 與接口中指定的name一致
 * targetNamespace 與接口中的命名空間一致,一般是接口的包名反轉
 * endpointInterface 接口地址
 */
@WebService(serviceName="UserService",//對外發布的服務名
        targetNamespace="http://service.wms.alibaba.com",//指定你想要的名稱空間,通常使用使用包名反轉
        endpointInterface="com.alibaba.wms.service.UserService")
@Component
public class UserServiceImpl implements UserService {

    private Map<String, User> userMap = new HashMap<String, User>();
    public UserServiceImpl() {
        System.out.println("向實體類插入數據");
        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、創建CXF類

package com.alibaba.wms.config;


import com.alibaba.wms.service.UserService;
import com.alibaba.wms.service.impl.UserServiceImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
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 {

    /**
     * 此方法作用是改變項目中服務名的前綴名,此處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
     */
    @Bean
    public ServletRegistrationBean disServlet() {
        return new ServletRegistrationBean(new CXFServlet(),"/soap/*");
    }

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

    @Autowired
    UserService userService;

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), userService);
        endpoint.publish("/UserService");
        return endpoint;
    }


   /* 非自動注入 UserService 的調用方式
    @Bean
    public UserService userService() {
        return new UserServiceImpl();
    }

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), userService());
        endpoint.publish("/UserService");
        return endpoint;
    }*/
}

6、開放訪問權限

package com.alibaba.wms.config;

import com.alibaba.commons.constants.PermitAllUrl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName:  ResourceServerConfig
 * @Description:TODO 資源服務配置
 */
@EnableResourceServer
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


   @Override
   public void configure(HttpSecurity http) throws Exception {
      http.csrf().disable().exceptionHandling()
            .authenticationEntryPoint(
                  (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
            .and().authorizeRequests()
            //非常重要,必須 放開權限的url,否則只有登錄之后才可以訪問
            .antMatchers(PermitAllUrl.permitAllUrl("/soap/**")).permitAll() 
            .anyRequest().authenticated().and().httpBasic();
   }

   @Bean
   public BCryptPasswordEncoder passwordEncoder() {
      return new BCryptPasswordEncoder();
   }
}

7、頁面訪問

8、編寫測試類

Client的pom文件引入

<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);
            // 創建一個代理接口實現
            UserService us = (UserService) jaxWsProxyFactoryBean.create();
            // 數據准備
            String userId = "111";
            // 調用代理接口的方法調用並返回結果
            String result = us.getUserName(userId);
            System.out.println("返回結果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

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

            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();//根節點
            Node node = root.getFirstChild();
            while (!node.getNodeName().equals("String")) {
                node = node.getFirstChild();
            }
            if (node.getFirstChild() != null) returnJson = node.getFirstChild().getNodeValue();
            System.out.println("獲取的返回參數為:" + 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”調用方法名
        sb.append("<userId>111</userId>"); //傳參,“userId”是配置在服務端的參數名稱,“111”是要傳入的參數值
        sb.append("</sam:getUserName>");
        sb.append("</soap:Body>");
        sb.append("</soap:Envelope>");
        return sb.toString();
    }


}

9、參考鏈接:

springboot整合CXF - 簡書 (jianshu.com)


免責聲明!

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



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