SpringBoot整合WebService(含源码)

  1. WebService是一种跨编程语言和跨操作系统平台的远程调用技术。

  2. WebService采用HTTP协议传输数据,采用XML格式封装数据(即XML中说明调用远程服务对象的哪个方法,传递的参数是什么,以及服务对象的 返回结果是什么)。XML是WebService平台中表示数据的格式。除了易于建立和易于分析外,XML主要的优点在于它既是平台无关的,又是厂商无关 的。无关性是比技术优越性更重要的:软件厂商是不会选择一个由竞争对手所发明的技术的。

  3. XSD(XML Schema)定义了一套标准的数据类型,并给出了一种语言来扩展这套数据类型。WebService平台就是用XSD来作为其数据类型系统的。当你用某种语言(如VB.NET或C#)来构造一个Web service时,为了符合WebService标准,所有你使用的数据类型都必须被转换为XSD类型。

  4. SOAP: WebService通过HTTP协议发送请求和接收结果时,发送的请求内容和结果内容都采用XML格式封装,并增加了一些特定的HTTP消息头,以说明 HTTP消息的内容格式,这些特定的HTTP消息头和XML内容格式就是SOAP协议。SOAP提供了标准的RPC方法来调用Web Service。

  5. SOAP协议 = HTTP协议 + XML数据格式

  6. SOAP协议定义了SOAP消息的格式,SOAP协议是基于HTTP协议的,SOAP也是基于XML和XSD的,XML是SOAP的数据编码方式。

  7. WSDL(Web Services Description Language)是基于XML的语言,用于描述Web Service及其函数、参数和返回值。它是WebService客户端和服务器端都能理解的标准格式。因为是基于XML的,所以WSDL既是机器可阅读的,又是人可阅读的,这将是一个很大的好处。一些最新的开发工具既能根据你的 Web service生成WSDL文档,又能导入WSDL文档,生成调用相应WebService的代理类代码。

  8. WSDL文件保存在Web服务器上,通过一个url地址就可以访问到它。客户端要调用一个WebService服务之前,要知道该服务的WSDL文件的地址。 WebService服务提供商可以通过两种方式来暴露它的WSDL文件地址:1.注册到UDDI服务器,以便被人查找;2.直接告诉给客户端调用者。

  9. 适用场合

    1. 跨防火墙通信
    2. 应用程序集成
    3. B2B集成
    4. 软件和数据重用
  10. 下面介绍在SpringBoot集成WebService的代码实现过程

  11. 新建一个SpringBoot工程

  12. 导入相关的依赖

    <dependencies>
        <!-- SpringBoot依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- SpringBoot整合WebService依赖 -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>3.2.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
  13. 修改SpringBoot配置文件application.properties为application.yml,并配置下面的配置项

    server:
      port: 8081
    
  14. 新增一个测试的实体类

    package com.kangswx.springbootwebservice.entity;
    
    import java.io.Serializable;
    
    public class User implements Serializable {
    
        private static final long serialVersionUID = -3718315085738793442L;
    
        private Integer id;
        private String name;
        private String email;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
    }
    
  15. 创建WebService接口类

    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebResult;
    import javax.jws.WebService;
    
    /**
     * WebService接口
     * WebService(targetNamespace = "http://service.springbootwebservice.kangswx.com")
     * 如果不添加的话,动态调用invoke的时候,会报找不到接口内的方法
     */
    @WebService(targetNamespace = "http://service.springbootwebservice.kangswx.com")
    public interface UserService {
    
        @WebMethod  //标注该方法为webservice暴露的方法,用于向外公布,它修饰的方法是webservice方法
        String getUser(@WebParam(name = "id") int id);
    
        @WebMethod
        @WebResult(name = "String", targetNamespace = "")
        String getUserName(@WebParam(name = "id") int id);
    }
    
  16. 创建WebService实现类

    import com.alibaba.fastjson.JSONObject;
    import com.kangswx.springbootwebservice.entity.User;
    import com.kangswx.springbootwebservice.service.UserService;
    import org.springframework.stereotype.Component;
    
    import javax.jws.WebService;
    import java.util.HashMap;
    import java.util.Map;
    
    @WebService(serviceName = "UserService",  //对外发布的服务名
            //指定名称空间,通常为包名反转
            targetNamespace = "http://service.springbootwebservice.kangswx.com",
            //服务接口全路径, 指定做SEI(Service EndPoint Interface)服务端点接口
            endpointInterface = "com.kangswx.springbootwebservice.service.UserService")
    @Component
    public class UserServiceImpl implements UserService {
    
        private Map<Integer, User> userMap = new HashMap<>();
    
        public UserServiceImpl(){
            System.out.println("初始化userMap");
            User user = new User();
            user.setId(1);
            user.setName("张三");
            user.setEmail("zhangsan@test.com");
            userMap.put(user.getId(), user);
    
            User user1 = new User();
            user1.setId(2);
            user1.setName("李四");
            user1.setEmail("lisi@test.com");
            userMap.put(user1.getId(), user1);
    
            User user2 = new User();
            user2.setId(3);
            user2.setName("王五");
            user2.setEmail("wangwu@test.com");
            userMap.put(user2.getId(), user2);
    
        }
    
        @Override
        public String getUser(int id) {
            return JSONObject.toJSONString(userMap.get(id));
        }
    
        @Override
        public String getUserName(int id) {
            System.out.println("getUserName: "+id);
            return userMap.get(id).getName();
        }
    
    }
    
  17. 创建WebService的发布配置类

    import com.kangswx.springbootwebservice.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
        private 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 servletRegistrationBean(){
            return new ServletRegistrationBean(new CXFServlet(), "/soap/*");
        }
    
        /**
         * JAX-WS
         * 站点服务
         * @return
         */
        @Bean
        public Endpoint endpoint(){
            EndpointImpl endpoint = new EndpointImpl(bus, userService);
            endpoint.publish("/user");
            return endpoint;
        }
    
    }
    
  18. 编写测试类测试上面的接口

    import com.kangswx.springbootwebservice.service.UserService;
    import org.apache.cxf.endpoint.Client;
    import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
    import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
    import org.junit.Test;
    
    /**
     * 两种不同的方式来调用webservice服务
     *     1:代理工厂方式
     *     2:动态调用webservice
     */
    public class UserServiceTest {
    
        /**
         * 代理工厂的方式,需要拿到对方的接口地址
         */
        @Test
        public void getUserTest1() {
            // 接口地址
            String address = "http://192.168.9.187:8081/soap/user?wsdl";
    
            // 代理工厂
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
    
            // 设置代理地址
            jaxWsProxyFactoryBean.setAddress(address);
    
            // 设置接口类型
            jaxWsProxyFactoryBean.setServiceClass(UserService.class);
    
            // 创建一个代理接口实现
            UserService us = (UserService) jaxWsProxyFactoryBean.create();
    
            //测试数据
            int id = 2;
    
            // 调用代理接口的方法调用并返回结果
            String userName = us.getUserName(id);
            System.out.println("返回结果: "+userName);
        }
    
        /**
         * 动态调用
         */
        @Test
        public void getUserNameTest2() {
            // 创建动态客户端
            JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
            Client client = dcf.createClient("http://192.168.9.187:8081/soap/user?wsdl");
    
            // 需要密码的情况需要加上用户名和密码
            // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
    
            Object[] objects = new Object[0];
            try {
                // invoke("方法名",参数1,参数2,参数3....);
                objects = client.invoke("getUserName", 2);
                System.out.println("返回数据:" + objects[0]);
            } catch (java.lang.Exception e) {
                e.printStackTrace();
            }
        }
    }
    
  19. 具体代码的实现过程见 SpringBoot整合WebService代码示例

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值