客户网站 备案,淘宝详情页设计模板,做网站如何月入10万,做网站app需要懂些什么软件目录 Web服务介绍Web服务的两种类型Web服务架构Web服务的主要特点Web服务使用场景Web服务标准和技术 WebService介绍WebService的作用适用场景不适用场景 WebService的原理三个角色相关概念 WebService开发框架代码实现服务端1.引入依赖2.实体类3.业务层接口接口实现类 4.配置类… 目录 Web服务介绍Web服务的两种类型Web服务架构Web服务的主要特点Web服务使用场景Web服务标准和技术 WebService介绍WebService的作用适用场景不适用场景 WebService的原理三个角色相关概念 WebService开发框架代码实现服务端1.引入依赖2.实体类3.业务层接口接口实现类 4.配置类5.拦截器6.启动 客户端1.引入依赖2.拦截器3.实体类4.调用类5.接口测试 遇到的问题 Web服务介绍
Web服务的两种类型
SOAP Web服务基于SOAPSimple Object Access Protocol协议的Web服务。SOAP是一种用于交换结构化信息的协议它使用XML作为消息格式并通常通过HTTP协议进行传输。RESTful Web服务基于RESTRepresentational State Transfer原则的Web服务。RESTful服务使用标准的HTTP方法如GET、POST、PUT、DELETE来执行操作并通常返回JSON或XML格式的数据。
Web服务架构
Web服务的架构通常包括以下关键组件
服务提供者Service Provider提供Web服务的实体。它们发布服务并处理来自客户端的请求。服务请求者Service Requestor使用Web服务的客户端应用程序。它们向服务提供者发送请求并处理响应。服务描述Service DescriptionWeb服务的描述文件通常使用WSDLWeb Services Description Language或OpenAPI等格式来描述服务的接口和操作。消息格式Message FormatWeb服务使用的数据交换格式通常是XML或JSON。通信协议Communication ProtocolWeb服务之间通信的协议常见的包括HTTP、HTTPS、SMTP等。
Web服务的主要特点
跨平台性Platform Independence由于Web服务使用标准化的协议和数据格式因此它们可以在不同的平台和操作系统上运行。松耦合Loose CouplingWeb服务通过标准化接口进行通信服务提供者和请求者之间的耦合度较低可以独立开发和部署。可组合性Composability可以通过组合多个Web服务来创建复杂的应用程序。可重用性ReusabilityWeb服务可以被多个应用程序重复使用从而提高了软件开发效率。易于维护Maintainability由于Web服务使用标准化的接口和协议因此易于维护和更新。
Web服务使用场景
Web服务在许多场景下都得到了广泛应用包括但不限于
企业应用集成Enterprise Application IntegrationEAI将不同的企业应用程序和系统集成在一起实现数据和业务流程的无缝交互。分布式系统构建分布式系统和服务导向架构Service-Oriented ArchitectureSOA提供跨网络的服务和资源共享。移动应用程序开发通过Web服务为移动应用程序提供数据和功能支持与后端服务器进行通信和交互。云计算在云平台上部署和管理Web服务提供云端服务和资源。
Web服务标准和技术
SOAPSimple Object Access Protocol用于构建基于XML的Web服务的协议。WSDLWeb Services Description Language用于描述Web服务的接口和操作的XML格式的语言。UDDIUniversal Description, Discovery, and Integration用于注册和发现Web服务的协议和规范。RESTRepresentational State Transfer一种基于HTTP协议的软件架构风格用于构建RESTful Web服务。JSONJavaScript Object Notation一种轻量级的数据交换格式通常用于RESTful Web服务的数据格式。
WebService介绍
WebService是一个SOA面向服务的编程的架构它是不依赖于语言不依赖于平台可以实现不同的语言间的相互调用通过Internet进行基于Http协议的网络应用间的交互。其实WebService并不是什么神秘的东西它就是一个可以远程调用的类或者说是组件把你本地的功能开放出去共别人调用。具体的说Web Service可以让你的网站使用其他网站的资源比如在网页上显示天气、地图、twitter上的最新动态等等。
WebService的作用
比如你的项目需要查询某银行账户余额。你能直接查吗肯定不行因为数据库是银行的他不可能给你权限。你想访问他的数据库获取数据这就需要用到WebService。通过调用银行暴露的接口来得到你想要的数据。
适用场景
软件的集成和复用如气象局(服务端系统)、天气查询网站等。 发布一个服务(对内/对外)不考虑客户端类型不考虑性能建议WebService服务端已经确定使用webservice客户端不能选择必须使用WebService 软件集成即通过远程调用技术,将两个系统整合到一起,从而实现软件集成。软件复用即同一个款软件的多次集成,最终实现复用。
不适用场景
考虑性能时不建议使用WebService采用xml格式封装数据,所以在传输过程中,要传输额外的标签,随着soap协议的不断完善,标签越来越大,导致webservice的性能下降。同构程序下不建议使用webservice比如java 用RMI不需要翻译成XML的数据。
WebService的原理
三个角色
在Web Service的体系架构中有三个角色服务提供者(Service Provider)也叫服务生产者服务请求者(Service Requester)也叫服务消费者服务注册中心(Service Register)也叫服务代理服务提供者在这里发布服务服务请求者在这里查找服务获取服务的绑定信息。
发布(Publish)服务提供者把服务按照规范格式发布到服务注册中心查找(Find)服务请求者根据服务注册中心提供的规范接口发出查找请求获取绑定服务所需的相关信息。绑定(Bind)服务请求者根据服务绑定信息对自己的系统进行配置从而可以调用服务提供者提供的服务。 相关概念
Web Service的实现是通过SOAP在Web上提供的软件服务使用WSDL文件进行说明并通过UDDI进行注册。
XML(Extensible Markup Language)扩展型可标记语言。面向短期的临时数据处理、面向万维网络是SOAP的基础。SOAP(Simple Object Access Protocol)简单对象存取协议。是XML Web Service 的通信协议。当用户通过UDDI找到你的WSDL描述文档后他通过可以SOAP调用你建立的Web服务中的一个或多个操作。SOAP是XML文档形式的调用方法的规范它可以支持不同的底层接口像HTTP(S)或者SMTP。WSDL(Web Services Description Language) WSDL 文件是一个 XML 文档用于说明一组 SOAP 消息以及如何交换这些消息。大多数情况下由软件自动生成和使用。UDDI (Universal Description, Discovery, and Integration) 是一个主要针对Web服务供应商和使用者的新项目。在用户能够调用Web服务之前必须确定这个服务内包含哪些商务方法找到被调用的接口定义还要在服务端来编制软件UDDI是一种根据描述文档来引导系统查找相应服务的机制。UDDI利用SOAP消息机制标准的XML/HTTP来发布编辑浏览以及查找注册信息。它采用XML格式来封装各种不同类型的数据并且发送到注册中心或者由注册中心来返回需要的数据。
WebService开发框架
WebService服务端是以远程接口为主的在Java实现的WebService技术里主要依靠CXF开发框架而这个CXF开发框架可以直接将接口发布成WebService。CXF又分为JAX-WS和JAX-RSJAX-WS是基于xml协议而JAX-RS是基于Restful风格两者的区别如下 RS基于Restful风格WS基于SOAP的XML协议RS比WS传输的数据更少效率更高WS只能传输XML数据RS可以传输XML也可以传输JSON
代码实现
服务端
1.引入依赖 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web-services/artifactId/dependency!-- apache-cxf --dependencygroupIdorg.apache.cxf/groupIdartifactIdcxf-rt-frontend-jaxws/artifactIdversion3.1.6/version/dependencydependencygroupIdorg.apache.cxf/groupIdartifactIdcxf-rt-transports-http/artifactIdversion3.1.6/version/dependency!-- apache-cxf 此处与上处二选其一 --dependencygroupIdorg.apache.cxf/groupIdartifactIdcxf-spring-boot-starter-jaxws/artifactIdversion3.5.2/version/dependency2.实体类
package com.cxf.pojo;import lombok.*;
import lombok.experimental.Accessors;import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;/*** author: zjl* datetime: 2024/3/29* desc:*/
Data
ToString
Builder
NoArgsConstructor
AllArgsConstructor
XmlRootElement
Accessors(chain true)
public class UserInfo implements Serializable {private static final long serialVersionUID 1L;private Long id;private String username;private String password;
}3.业务层
接口
package com.cxf.service;import com.cxf.pojo.UserInfo;import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;WebService(name userInfoService, targetNamespace http://server.service.cxf.com)
public interface UserInfoService {WebMethod(operationName saveUserInfo)void saveUserInfo(WebParam(name userInfo) UserInfo userInfo);WebMethodUserInfo getUserInfoById(WebParam(name id) Long id);
}接口实现类
package com.cxf.service;import com.alibaba.fastjson.JSON;
import com.cxf.pojo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;import javax.jws.WebService;/*** WebService涉及到的有这些 四解三类 , 即四个注解三个类* WebMethod* WebService* WebResult* WebParam* SpringBus* Endpoint* EndpointImpl** 一般我们都会写一个接口然后再写一个实现接口的实现类但是这不是强制性的* WebService 注解表明是一个webservice服务。* name对外发布的服务名, 对应于wsdl:portType nameServerServiceDemo/wsdl:portType* targetNamespace命名空间,一般是接口的包名倒序, 实现类与接口类的这个配置一定要一致这种错误* Exception in thread main org.apache.cxf.common.i18n.UncheckedException: No operation was found with the name xxxx* 对应于targetNamespacehttp://server.webservice.example.com* endpointInterface服务接口全路径如果是没有接口直接写实现类的该属性不用配置, 指定做SEIService EndPoint Interface服务端点接口* serviceName对应于wsdl:service nameServerServiceDemoImplService/wsdl:service* portName对应于wsdl:port bindingtns:ServerServiceDemoImplServiceSoapBinding nameServerServiceDemoPort/wsdl:port** WebMethod 表示暴露的服务方法, 这里有接口ServerServiceDemo存在在接口方法已加上WebMethod, 所以在实现类中不用再加上否则就要加上* operationName: 接口的方法名* action: 没发现又什么用处* exclude: 默认是false, 用于阻止将某一继承方法公开为web服务** WebResult 表示方法的返回值* name返回值的名称* partName* targetNamespace:* header: 默认是false, 是否将参数放到头信息中用于保护参数默认在body中** WebParam* name接口的参数* partName* targetNamespace:* header: 默认是false, 是否将参数放到头信息中用于保护参数默认在body中* modelWebParam.Mode.IN/OUT/INOUT*/
Service
WebService(serviceName userInfoService, targetNamespace http://server.webservice.gtp.sinotrans.com, endpointInterface com.sinotrans.gtp.webservice.UserInfoService)
Slf4j
public class UserInfoServiceImpl implements UserInfoService {Overridepublic void saveUserInfo(UserInfo userInfo) {System.out.println(保存用户信息成功 userInfo.toString());}Overridepublic UserInfo getUserInfoById(Long id) {UserInfo zhangsan UserInfo.builder().id(1L).username(zhangsan).password(123456).build();log.info(JSON.toJSONString(zhangsan));return zhangsan;}
}4.配置类
package com.cxf.config;import com.cxf.interceptor.WebServiceAuthInterceptor;
import com.cxf.service.UserInfoService;
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.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.annotation.Resource;
import javax.xml.ws.Endpoint;/*** author: zjl* datetime: 2024/3/29* desc:*/
Configuration
public class WebServiceConfig {Resourceprivate UserInfoService userInfoService;/* Resourceprivate AgeInfoService ageInfoService;*/
/* Resourceprivate 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)public SpringBus springBus() {return new SpringBus();}/*** 设置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*/Beanpublic ServletRegistrationBean getRegistrationBean() {return new ServletRegistrationBean(new CXFServlet(), /webServices/*);}Beanpublic Endpoint messageEndPoint() {EndpointImpl endpoint new EndpointImpl(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;
// }
}5.拦截器
package com.cxf.interceptor;import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.stereotype.Component;
import org.w3c.dom.NodeList;import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;/*** author: zjl* datetime: 2024/3/29* desc:*/
Component
Slf4j
public class WebServiceAuthInterceptor extends AbstractPhaseInterceptorSoapMessage {/*** 用户名*/private static final String USER_NAME kgc;/*** 密码*/private static final String USER_PASSWORD kgc.com;private static final String NAME_SPACE_URI http://server.service.cxf.com;/*** 创建拦截器*/private SAAJInInterceptor interceptor new SAAJInInterceptor();public WebServiceAuthInterceptor() {super(Phase.PRE_PROTOCOL);//添加拦截super.getAfter().add(SAAJInInterceptor.class.getName());}Overridepublic void handleMessage(SoapMessage message) throws Fault {//获取指定消息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) {throw new Fault(new IllegalAccessException(没有Header信息无法实现用户认证处理!));}//SOAP是基于XML文件结构进行传输的所以如果要想获取认证信息就必须进行相关的结构约定NodeList usernameNodeList header.getElementsByTagNameNS(NAME_SPACE_URI, username);NodeList passwordNodeList header.getElementsByTagNameNS(NAME_SPACE_URI, password);if (usernameNodeList.getLength() 1) {throw new Fault(new IllegalAccessException(没有用户信息无法实现用户认证处理!));}if (passwordNodeList.getLength() 1) {throw new Fault(new IllegalAccessException(没有密码信息无法实现用户认证处理!));}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 new SOAPException(用户认证失败!);log.info(用户认证失败!);throw new Fault(soapException);}}
}6.启动
http://localhost:8080/webServices/点击链接可以查看到具体的接口信息
客户端
1.引入依赖 dependencygroupIdorg.apache.cxf/groupIdartifactIdcxf-spring-boot-starter-jaxws/artifactIdversion3.5.2/version/dependency!-- 添加 FastJSON依赖 --!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --dependencygroupIdcom.alibaba/groupIdartifactIdfastjson/artifactIdversion1.2.9/version/dependency2.拦截器
package com.cxf.interceptor;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.headers.Header;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import java.util.List;/*** author: zjl* datetime: 2024/3/29* desc:*/
public class ClientLoginInterceptor extends AbstractPhaseInterceptorSoapMessage {private String username;private String password;private static final String NAME_SPACE_URI http://server.service.cxf.com;public ClientLoginInterceptor(String username, String password) {super(Phase.PREPARE_SEND);this.username username;this.password password;}Overridepublic void handleMessage(SoapMessage soapMessage) throws Fault {ListHeader 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, new Header(new QName(authority), authority));}
}3.实体类
package com.cxf.pojo;import lombok.*;
import lombok.experimental.Accessors;import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;/*** author: zjl* datetime: 2024/3/29* desc:*/
Data
ToString
Builder
NoArgsConstructor
AllArgsConstructor
XmlRootElement
Accessors(chain true)
public class UserInfo implements Serializable {private static final long serialVersionUID 1L;private Long id;private String username;private String password;
}4.调用类
package com.cxf.webservice;import com.cxf.interceptor.ClientLoginInterceptor;
import com.cxf.pojo.UserInfo;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.stereotype.Component;/*** author: zjl* datetime: 2024/3/29* desc:*/
Component
public class UserInfoApiClient {private static final String USERNAME kgc;private static final String PASSWORD kgc.com;private static final String ADDRESS http://localhost:8080/webServices/userInfoService?wsdl;/*** 使用动态代理* param id* throws Exception*/public String getUserInfoByIdWithDynamic(Long id) throws Exception {JaxWsDynamicClientFactory clientFactory JaxWsDynamicClientFactory.newInstance();Client client clientFactory.createClient(ADDRESS);client.getOutInterceptors().add(new ClientLoginInterceptor(USERNAME, PASSWORD));Object[] userInfos client.invoke(getUserInfoById, id);String userInfo JSON.toJSONString(userInfos[0]);System.out.println(JSON.toJSON(userInfo));return userInfo;}
}5.接口测试
package com.cxf.controller;import com.cxf.webservice.UserInfoApiClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;/*** author: zjl* datetime: 2024/3/29* desc:*/
RestController
public class UserInfoController {Resourceprivate UserInfoApiClient userInfoApiClient;RequestMapping(/test)public Object getUserInfoById(Long id) throws Exception {return userInfoApiClient.getUserInfoByIdWithDynamic(1L);}
}遇到的问题
Unable to create schema compiler] with root cause
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Unable to create schema compiler] with root causejava.lang.ClassNotFoundException: com/sun/tools/internal/xjc/api/XJCat java.base/java.lang.Class.forName0(Native Method) ~[na:na]at java.base/java.lang.Class.forName(Class.java:467) ~[na:na]at org.apache.cxf.common.jaxb.JAXBUtils.createSchemaCompiler(JAXBUtils.java:708) ~[cxf-core-3.5.2.jar:3.5.2]at org.apache.cxf.common.jaxb.JAXBUtils.createSchemaCompilerWithDefaultAllocator(JAXBUtils.java:722) ~[cxf-core-3.5.2.jar:3.5.2]at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createSchemaCompiler(DynamicClientFactory.java:447) ~[cxf-rt-frontend-simple-3.5.2.jar:3.5.2]at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:327) ~[cxf-rt-frontend-simple-3.5.2.jar:3.5.2]at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:245) ~[cxf-rt-frontend-simple-3.5.2.jar:3.5.2]at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:238) ~[cxf-rt-frontend-simple-3.5.2.jar:3.5.2]at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:192) ~[cxf-rt-frontend-simple-3.5.2.jar:3.5.2]at com.kgc.webservice.UserInfoApiClient.getUserInfoWithDynamic(UserInfoApiClient.java:19) ~[classes/:na]at com.kgc.controller.UserInfoController.getUserInfoById(UserInfoController.java:22) ~[classes/:na]因为工程创建的时候是springBoot3.2.4jdk17我把SpringBoot和JDK版本都降低了然后写的代码降低后的JDK是1.8但是project中的sdk还是17把sdk换成一致就可以了。