0


SpringBoot 整合WebService详解

1. 概述

WebService服务端是以远程接口为主的,在Java实现的WebService技术里主要依靠CXF开发框架,而这个CXF开发框架可以直接将接口发布成WebService。
CXF又分为JAX-WS和JAX-RS,JAX-WS是基于xml协议,而JAX-RS是基于Restful风格,两者的区别如下:

  • RS基于Restful风格,WS基于SOAP的XML协议
  • RS比WS传输的数据更少,效率更高
  • WS只能传输XML数据,RS可以传输XML,也可以传输JSON

参考:

https://blog.csdn.net/liu320yj/article/details/121740367

https://www.cnblogs.com/myitnews/p/12370308.html

https://juejin.cn/post/6872881983937069063

此处讲解JAX-WS

2. 开发

2.1. maven依赖

<!--WebService--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web-services</artifactId></dependency><!-- CXF webservice --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-spring-boot-starter-jaxws</artifactId><version>3.4.5</version></dependency>

2.2. 新建实体类

/**
 * @Author:wangdi
 * @Date:2023/4/23 14:04
 * @Des: UserInfo
 */@Data@ToString@Builder@NoArgsConstructor@AllArgsConstructor@XmlRootElement@Accessors(chain =true)publicclassUserInfoimplementsSerializable{privatestaticfinallong serialVersionUID =-5352429333001227976L;privateLong id;privateString username;privateString password;}

2.3. 新建接口

importjavax.jws.WebMethod;importjavax.jws.WebParam;importjavax.jws.WebService;/**
 * @Author:wangdi
 * @Date:2023/4/23 14:05
 * @Des: UserInfoService
 */@WebService(name ="userInfoService", targetNamespace ="http://server.webservice.gtp.sinotrans.com")publicinterfaceUserInfoService{@WebMethod(operationName ="saveUserInfo")voidsaveUserInfo(@WebParam(name ="userInfo")UserInfo userInfo);@WebMethodUserInfogetUserInfoById(@WebParam(name ="id")Long id);}

2.4. [服务端开发] 接口实现类

importcom.sinotrans.framework.common.utils.JsonUtil;importcom.sinotrans.gtp.entity.UserInfo;importcom.sinotrans.gtp.webservice.UserInfoService;importlombok.extern.slf4j.Slf4j;importorg.springframework.stereotype.Service;importjavax.jws.WebService;/**
 * @Author:wangdi
 * @Date:2023/4/23 14:06
 * @Des: UserInfoServiceImpl
 *//**
 * WebService涉及到的有这些 "四解三类 ", 即四个注解,三个类
 * @WebMethod
 * @WebService
 * @WebResult
 * @WebParam
 * SpringBus
 * Endpoint
 * EndpointImpl
 *
 * 一般我们都会写一个接口,然后再写一个实现接口的实现类,但是这不是强制性的
 * @WebService 注解表明是一个webservice服务。
 *      name:对外发布的服务名, 对应于<wsdl:portType name="ServerServiceDemo"></wsdl:portType>
 *      targetNamespace:命名空间,一般是接口的包名倒序, 实现类与接口类的这个配置一定要一致这种错误
 *              Exception in thread "main" org.apache.cxf.common.i18n.UncheckedException: No operation was found with the name xxxx
 *              对应于targetNamespace="http://server.webservice.example.com"
 *      endpointInterface:服务接口全路径(如果是没有接口,直接写实现类的,该属性不用配置), 指定做SEI(Service EndPoint Interface)服务端点接口
 *      serviceName:对应于<wsdl:service name="ServerServiceDemoImplService"></wsdl:service>
 *      portName:对应于<wsdl:port binding="tns:ServerServiceDemoImplServiceSoapBinding" name="ServerServiceDemoPort"></wsdl:port>
 *
 * @WebMethod 表示暴露的服务方法, 这里有接口ServerServiceDemo存在,在接口方法已加上@WebMethod, 所以在实现类中不用再加上,否则就要加上
 *      operationName: 接口的方法名
 *      action: 没发现又什么用处
 *      exclude: 默认是false, 用于阻止将某一继承方法公开为web服务
 *
 * @WebResult 表示方法的返回值
 *      name:返回值的名称
 *      partName:
 *      targetNamespace:
 *      header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中
 *
 * @WebParam
 *       name:接口的参数
 *       partName:
 *       targetNamespace:
 *       header: 默认是false, 是否将参数放到头信息中,用于保护参数,默认在body中
 *       model:WebParam.Mode.IN/OUT/INOUT
 */@Service@WebService(serviceName ="userInfoService", targetNamespace ="http://server.webservice.gtp.sinotrans.com", endpointInterface ="com.sinotrans.gtp.webservice.UserInfoService")@Slf4jpublicclassUserInfoServiceImplimplementsUserInfoService{@OverridepublicvoidsaveUserInfo(UserInfo userInfo){System.out.println("保存用户信息成功"+ userInfo.toString());}@OverridepublicUserInfogetUserInfoById(Long id){UserInfo zhangsan =UserInfo.builder().id(1L).username("zhangsan").password("123456").build();
        log.info(JsonUtil.toJson(zhangsan));return zhangsan;}}

2.5. 配置类

importcom.sinotrans.gtp.interceptor.WebServiceAuthInterceptor;importcom.sinotrans.gtp.webservice.AgeInfoService;importcom.sinotrans.gtp.webservice.UserInfoService;importorg.apache.cxf.Bus;importorg.apache.cxf.bus.spring.SpringBus;importorg.apache.cxf.jaxws.EndpointImpl;importorg.apache.cxf.transport.servlet.CXFServlet;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.web.servlet.ServletRegistrationBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjavax.xml.ws.Endpoint;/**
 * @Author:wangdi
 * @Date:2023/4/23 14:07
 * @Des: CXFConfig
 */@ConfigurationpublicclassWebServiceConfig{@AutowiredprivateUserInfoService userInfoService;@AutowiredprivateAgeInfoService ageInfoService;//    @Autowired//    private WebServiceAuthInterceptor interceptor;/**
     * Apache CXF 核心架构是以BUS为核心,整合其他组件。
     * Bus是CXF的主干, 为共享资源提供一个可配置的场所,作用类似于Spring的ApplicationContext,这些共享资源包括
     * WSDl管理器、绑定工厂等。通过对BUS进行扩展,可以方便地容纳自己的资源,或者替换现有的资源。默认Bus实现基于Spring架构,
     * 通过依赖注入,在运行时将组件串联起来。BusFactory负责Bus的创建。默认的BusFactory是SpringBusFactory,对应于默认
     * 的Bus实现。在构造过程中,SpringBusFactory会搜索META-INF/cxf(包含在 CXF 的jar中)下的所有bean配置文件。
     * 根据这些配置文件构建一个ApplicationContext。开发者也可以提供自己的配置文件来定制Bus。
     */@Bean(name =Bus.DEFAULT_BUS_ID)publicSpringBusspringBus(){returnnewSpringBus();}/**
     * 设置WebService访问父路径
     * <p>
     * 此方法作用是改变项目中服务名的前缀名,此处127.0.0.1或者localhost不能访问时,请使用ipconfig查看本机ip来访问
     * 此方法被注释后, 即不改变前缀名(默认是services), wsdl访问地址为 http://127.0.0.1:8080/services/ws/api?wsdl
     * 去掉注释后wsdl访问地址为:http://127.0.0.1:8080/webServices/ws/api?wsdl
     * http://127.0.0.1:8080/soap/列出服务列表 或 http://127.0.0.1:8080/soap/ws/api?wsdl 查看实际的服务
     * 新建Servlet记得需要在启动类添加注解:@ServletComponentScan
     * 如果启动时出现错误:not loaded because DispatcherServlet Registration found non dispatcher servlet dispatcherServlet
     * 可能是springboot与cfx版本不兼容。
     * 同时在spring boot2.0.6之后的版本与xcf集成,不需要在定义以下方法,直接在application.properties配置文件中添加:
     * cxf.path=/service(默认是services)
     */@BeanpublicServletRegistrationBeangetRegistrationBean(){returnnewServletRegistrationBean(newCXFServlet(),"/webServices/*");}@BeanpublicEndpointmessageEndPoint(){EndpointImpl endpoint =newEndpointImpl(springBus(),this.userInfoService);
        endpoint.publish("/userInfoService");//        endpoint.getInInterceptors().add(this.interceptor);return endpoint;}/*用于发布多个WebService*///    @Bean//    public Endpoint messageEndPoint2() {//        EndpointImpl endpoint = new EndpointImpl(springBus(), this.ageInfoService);//        endpoint.publish("/userInfoService");        endpoint.getInInterceptors().add(this.interceptor);//        return endpoint;//    }}

2.6. 拦截器类(如有需要)

importlombok.extern.slf4j.Slf4j;importorg.apache.cxf.binding.soap.SoapMessage;importorg.apache.cxf.binding.soap.saaj.SAAJInInterceptor;importorg.apache.cxf.interceptor.Fault;importorg.apache.cxf.phase.AbstractPhaseInterceptor;importorg.apache.cxf.phase.Phase;importorg.springframework.stereotype.Component;importorg.w3c.dom.NodeList;importjavax.xml.soap.SOAPException;importjavax.xml.soap.SOAPHeader;importjavax.xml.soap.SOAPMessage;/**
 * @Author:wangdi
 * @Date:2023/4/23 14:10
 * @Des: WebServiceAuthInterceptor
 */@Component@Slf4jpublicclassWebServiceAuthInterceptorextendsAbstractPhaseInterceptor<SoapMessage>{/**
     * 用户名
     */privatestaticfinalString USER_NAME ="wangdi";/**
     * 密码
     */privatestaticfinalString USER_PASSWORD ="wangdi.com";privatestaticfinalString NAME_SPACE_URI ="http://server.webservice.gtp.sinotrans.com";/**
     * 创建拦截器
     */privateSAAJInInterceptor interceptor =newSAAJInInterceptor();publicWebServiceAuthInterceptor(){super(Phase.PRE_PROTOCOL);//添加拦截super.getAfter().add(SAAJInInterceptor.class.getName());}@OverridepublicvoidhandleMessage(SoapMessage message)throwsFault{//获取指定消息SOAPMessage soapMessage = message.getContent(SOAPMessage.class);if(null== soapMessage){this.interceptor.handleMessage(message);
            soapMessage = message.getContent(SOAPMessage.class);}//SOAP头信息SOAPHeader header =null;try{
            header = soapMessage.getSOAPHeader();}catch(SOAPException e){
            e.printStackTrace();}if(null== header){thrownewFault(newIllegalAccessException("没有Header信息,无法实现用户认证处理!"));}//SOAP是基于XML文件结构进行传输的,所以如果要想获取认证信息就必须进行相关的结构约定NodeList usernameNodeList = header.getElementsByTagNameNS(NAME_SPACE_URI,"username");NodeList passwordNodeList = header.getElementsByTagNameNS(NAME_SPACE_URI,"password");if(usernameNodeList.getLength()<1){thrownewFault(newIllegalAccessException("没有用户信息,无法实现用户认证处理!"));}if(passwordNodeList.getLength()<1){thrownewFault(newIllegalAccessException("没有密码信息,无法实现用户认证处理!"));}String username = usernameNodeList.item(0).getTextContent().trim();String password = passwordNodeList.item(0).getTextContent().trim();if(USER_NAME.equals(username)&& USER_PASSWORD.equals(password)){
            log.info("用户访问认证成功!");}else{SOAPException soapException =newSOAPException("用户认证失败!");
            log.info("用户认证失败!");thrownewFault(soapException);}}}

3. 启动

http://localhost:8080/webServices/

在这里插入图片描述

点击链接可以查看到具体的接口信息

在这里插入图片描述

4. [客户端] 开发

4.1. 新建客户端拦截器类(如有需要)

对应2.4

importorg.apache.cxf.binding.soap.SoapMessage;importorg.apache.cxf.helpers.DOMUtils;importorg.apache.cxf.interceptor.Fault;importorg.apache.cxf.phase.AbstractPhaseInterceptor;importorg.apache.cxf.phase.Phase;importorg.apache.cxf.headers.Header;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importjavax.xml.namespace.QName;importjava.util.List;/**
 * @Author:wangdi
 * @Date:2023/4/23 15:45
 * @Des: ClientLoginInterceptor
 */publicclassClientLoginInterceptorextendsAbstractPhaseInterceptor<SoapMessage>{privateString username;privateString password;privatestaticfinalString NAME_SPACE_URI ="http://server.webservice.gtp.sinotrans.com";publicClientLoginInterceptor(String username,String password){super(Phase.PREPARE_SEND);this.username = username;this.password = password;}@OverridepublicvoidhandleMessage(SoapMessage soapMessage)throwsFault{List<Header> headers = soapMessage.getHeaders();Document document =DOMUtils.createDocument();Element authority = document.createElementNS(NAME_SPACE_URI,"authority");Element username = document.createElementNS(NAME_SPACE_URI,"username");Element password = document.createElementNS(NAME_SPACE_URI,"password");
        username.setTextContent(this.username);
        password.setTextContent(this.password);
        authority.appendChild(username);
        authority.appendChild(password);
        headers.add(0,newHeader(newQName("authority"), authority));}}

4.2. 新建客户端调用接口

也可以在main方法中编写

调用之前 需要启动SpringBoot

importcom.sinotrans.gtp.entity.UserInfo;importcom.sinotrans.gtp.interceptor.ClientLoginInterceptor;importcom.sinotrans.gtp.webservice.UserInfoService;importorg.apache.cxf.endpoint.Client;importorg.apache.cxf.jaxws.JaxWsProxyFactoryBean;importorg.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;importorg.springframework.stereotype.Component;/**
 * @Author:wangdi
 * @Date:2023/4/23 15:51
 * @Des: UserInfoApiClient
 */@ComponentpublicclassUserInfoApiClient{privatestaticfinalString USERNAME ="wangdi";privatestaticfinalString PASSWORD ="wangdi.com";privatestaticfinalString ADDRESS ="http://localhost:8080/webServices/userInfoService?wsdl";/**
     * 使用代理方法
     * @param userInfo
     */publicvoidsaveUserInfoWithProxy(UserInfo userInfo){JaxWsProxyFactoryBean jaxWsProxyFactoryBean =newJaxWsProxyFactoryBean();
        jaxWsProxyFactoryBean.setAddress(ADDRESS);
        jaxWsProxyFactoryBean.setServiceClass(UserInfoService.class);
        jaxWsProxyFactoryBean.getOutInterceptors().add(newClientLoginInterceptor(USERNAME, PASSWORD));UserInfoService userInfoService =(UserInfoService) jaxWsProxyFactoryBean.create();
        userInfoService.saveUserInfo(userInfo);}/**
     * 使用动态代理
     * @param id
     * @throws Exception
     */publicvoidgetUserInfoByIdWithDynamic(Long id)throwsException{JaxWsDynamicClientFactory clientFactory =JaxWsDynamicClientFactory.newInstance();Client client = clientFactory.createClient(ADDRESS);
        client.getOutInterceptors().add(newClientLoginInterceptor(USERNAME, PASSWORD));Object[] userInfos = client.invoke("getUserInfoById", id);String userInfo = userInfos[0].toString();System.out.println(userInfo);}}

客户端使用动态代理访问时,参数中有bean对象时会提示类型转换错误异常

4.3. main方法中只显示INFO类日志

加入以下代码到类中

static{LoggerContext loggerContext =(LoggerContext)LoggerFactory.getILoggerFactory();List<Logger> loggerList = loggerContext.getLoggerList();
    loggerList.forEach(logger ->{
        logger.setLevel(Level.INFO);});}

5. Postmen中调用

可结合浏览器插件 Wizdler

地址栏输入Web Service 接口地址,选择post方式,Headers中设置Content-Type为

text/xml;charset=utf-8

在这里插入图片描述

<Envelopexmlns="http://schemas.xmlsoap.org/soap/envelope/"><Body><getUserInfoByIdxmlns="http://server.webservice.gtp.sinotrans.com"><idxmlns="">1</id></getUserInfoById></Body></Envelope>

6. 其他WebService调用方式

6.1. RestTemplate

maven依赖

<dependency><groupId>org.apache.cassandra</groupId><artifactId>cassandra-all</artifactId><version>0.8.1</version><exclusions><exclusion><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId></exclusion><exclusion><groupId>log4j</groupId><artifactId>log4j</artifactId></exclusion></exclusions></dependency>

配置类

/**
 * @Author:wangdi
 * @Date:2023/4/24 9:56
 * @Des: RestTemplateConfig
 */@ConfigurationpublicclassRestTemplateConfig{@BeanpublicRestTemplaterestTemplate(){HttpComponentsClientHttpRequestFactory factory =newHttpComponentsClientHttpRequestFactory();// 超时
        factory.setConnectionRequestTimeout(5000);
        factory.setConnectTimeout(5000);
        factory.setReadTimeout(5000);SSLConnectionSocketFactory sslsf =newSSLConnectionSocketFactory(createIgnoreVerifySSL(),// 指定TLS版本null,// 指定算法null,// 取消域名验证newHostnameVerifier(){@Overridepublicbooleanverify(String string,SSLSession ssls){returntrue;}});CloseableHttpClient httpClient =HttpClients.custom().setSSLSocketFactory(sslsf).build();
        factory.setHttpClient(httpClient);RestTemplate restTemplate =newRestTemplate(factory);// 解决中文乱码问题
        restTemplate.getMessageConverters().set(1,newStringHttpMessageConverter(StandardCharsets.UTF_8));return restTemplate;}publicstaticHttpHeadersgetWSHeaders(){HttpHeaders headers =newHttpHeaders();
        headers.setContentType(MediaType.TEXT_XML);List<MediaType> acceptableMediaTypes =newArrayList<MediaType>();
        acceptableMediaTypes.add(MediaType.TEXT_XML);
        headers.setAccept(acceptableMediaTypes);return headers;}/**
     * 跳过证书效验的sslcontext
     *
     * @return
     * @throws Exception
     */privateSSLContextcreateIgnoreVerifySSL(){try{SSLContext sc =SSLContext.getInstance("TLS");// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法X509TrustManager trustManager =newX509TrustManager(){@OverridepublicvoidcheckClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,String paramString)throwsCertificateException{}@OverridepublicvoidcheckServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,String paramString)throwsCertificateException{}@Overridepublicjava.security.cert.X509Certificate[]getAcceptedIssuers(){returnnull;}};
            sc.init(null,newTrustManager[]{trustManager},null);return sc;}catch(Exception e){
            e.printStackTrace();}returnnull;}}

调用测试

/**
 * @Author:wangdi
 * @Date:2023/4/24 9:58
 * @Des: RestTest
 */@Slf4jpublicclassRestTestextendsSinogtpApplicationTests{// 使用之前注入@AutowiredprivateRestTemplate rt;@Testpublicvoidtest(){String xml ="xml报文";String url ="调用地址";ResponseEntity<String> response =null;try{
            log.info("\n\n\n下发:"+ xml +"\n\n\n");HttpEntity<Object> requestEntity =newHttpEntity<Object>(xml,RestTemplateConfig.getWSHeaders());

            response = rt.exchange(url,HttpMethod.POST, requestEntity,String.class);}catch(RestClientResponseException e){
            log.error("\n\n\nError: "+ e.getResponseBodyAsString()+"\n\n\n");thrownewHttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR,"出错");}
        log.info(response.getBody());System.out.println();}}

6.2. 直接AXIS调用远程的web service

未验证

参考: https://cloud.tencent.com/developer/article/1148263

https://blog.csdn.net/LLLLLer/article/details/128103465

maven依赖

maven依赖(已验证)

<dependency><groupId>org.apache.axis</groupId><artifactId>axis</artifactId><version>1.4</version></dependency><dependency><groupId>commons-discovery</groupId><artifactId>commons-discovery</artifactId><version>0.2</version></dependency><dependency><groupId>org.apache.axis</groupId><artifactId>axis-jaxrpc</artifactId><version>1.4</version></dependency><dependency><groupId>org.apache.axis</groupId><artifactId>axis-saaj</artifactId><version>1.4</version></dependency>

测试

maven依赖(未验证)

//        //服务地址//        String url = "http://localhost:8080/webServices/userInfoService?wsdl";//        try {//            Service service = new Service();//            Call call = (Call) service.createCall();//            call.setTargetEndpointAddress(url);//            //第一个参数命名空间,第二个参数方法名            QName qname = new QName("命名空间", "接口名");//            QName qname = new QName("http://server.webservice.gtp.sinotrans.com", "getUserInfoById");//            call.setOperationName(qname);            call.addParameter("参数名", Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN);//            call.addParameter("id", Constants.XSD_LONG, javax.xml.rpc.ParameterMode.IN);//            //设置返回类型//            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//            //调用方法并传递参数 比如这样{\"NAME\":\"\"}            String resultStr = (String) call.invoke(new Object[]{"参数值"});//            String resultStr = (String) call.invoke(new Object[]{(long)1});//            System.out.println("服务调用结果:" + resultStr);//        } catch (Exception e) {//            e.printStackTrace();//        }

本文转载自: https://blog.csdn.net/qq_21480147/article/details/130341579
版权归原作者 bug–0/1 所有, 如有侵权,请联系我们删除。

“SpringBoot 整合WebService详解”的评论:

还没有评论