当前位置:网站首页>WebService service call
WebService service call
2022-06-09 09:47:00 【Ugly base】
Catalog
One 、 brief introduction
1、 What is? Web Service?
Web Service It is a kind of remote calling technology across programming languages and operating system platforms .Web Service Use standard SOAP(Simple Object Access Protocol, Simple object access protocol , Belong to w3c standard . And based on http Application layer protocol transport xml data ) Protocol transfer .Web Service use WSDL As a descriptive language , also W3C by Web Service Developed a set of transmission data types , Use xml Describe , namely XSD(XML Schema Datatypes), Written in any language web Service When sending data, the interface must be converted into WebService The standard XSD send out .
2、Web Service Three elements
Web Services Elements of the platform :
- SOAP( Simple Object Access Protocol );
- UDDI( General description 、 Discovery and integration );
- WSDL(Web services Description Language ).
2.1、SOAP
SOAP Also called simple object access protocol , It's a simple one based on xml The agreement , It enables applications to pass through HTTP To exchange data , It can be simply understood as SOAP= http+xml.SOAP The current mainstream version of the protocol is :SOAP1.1 and SOAP1.2.SOAP Neither Web Service Exclusive agreement of , Other applications can also use soap To transmit data .
2.1.1、SOAP Form of agreement
One SOAP News is a common XML file , Contains the following elements :
- Essential Envelope Elements , You can put this XML The document is identified as a SOAP news ;
- Optional Header Elements , Contains header information ;
- Essential Body Elements , All the information and responses contained in the call ;
- Optional Fault Elements , Provides information about errors that occurred while processing this message .
All the above elements are declared for SOAP Encapsulated in the default namespace :http://www.w3.org/2001/12/soap-envelope, And aiming at SOAP Default namespace for encoding and data types :
http://www.w3.org/2001/12/soap-encoding.
SOAP The basic structure of the message is as follows :
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
...
</soap:Header>
<soap:Body>
...
<soap:Fault>
...
</soap:Fault>
</soap:Body>
</soap:Envelope>
2.2、WSDL
WSDL( Network service description language ,Web Services Description Language) It's based on XML Language , Used to describe Web Services And how to access them ( Method , Enter the reference , Return value ). In a nutshell Web Service Instructions for use .
WSDL The document structure mainly includes 5 A label :
- <service> : Service view ,Web Service Service node of , It includes service endpoints ;
- <binding> : Define message format and protocol details for each service port ;
- <portType> : The most important WSDL Elements , It can describe a web service、 Operations that can be performed , And related news , You can put Element is compared to a function library in a traditional programming language ( Or a module 、 Or a class );
- <message> : Define the data elements of an operation , Each message consists of one or more components . These parts can be compared to the parameters of a function call in a traditional programming language ;
- <type> : Definition web service The type of data used , For maximum platform neutrality ,WSDL Use XML Schema Syntax to define data types .
Here's a WSDL A simplified fragment of a document :
<!-- Define data types -->
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="http://WebXml.com.cn/">
<s:element name="getMobileCodeInfo">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="mobileCode" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="userID" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>
<s:element name="getMobileCodeInfoResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="getMobileCodeInfoResult" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>
</s:schema>
</wsdl:types>
<!-- Define the data elements of the operation -->
<wsdl:message name="getMobileCodeInfoSoapIn">
<wsdl:part name="parameters" element="tns:getMobileCodeInfo"/>
</wsdl:message>
<wsdl:message name="getMobileCodeInfoSoapOut">
<wsdl:part name="parameters" element="tns:getMobileCodeInfoResponse"/>
</wsdl:message>
<!-- Define the actions that can be performed -->
<wsdl:portType name="MobileCodeWSSoap">
<wsdl:operation name="getMobileCodeInfo">
<wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"><br /><h3> Obtain the province to which the domestic mobile phone number belongs 、 Region and mobile card type information </h3><p> Input parameters :mobileCode = character string ( Phone number , At least before 7 Digit number ),userID = character string ( Business users ID) Free user is an empty string ; Return the data : character string ( Phone number : Province City Mobile card type ).</p><br /></wsdl:documentation>
<wsdl:input message="tns:getMobileCodeInfoSoapIn"/>
<wsdl:output message="tns:getMobileCodeInfoSoapOut"/>
</wsdl:operation>
</wsdl:portType>
<!-- Define message format and protocol details -->
<wsdl:binding name="MobileCodeWSSoap" type="tns:MobileCodeWSSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="getMobileCodeInfo">
<soap:operation soapAction="http://WebXml.com.cn/getMobileCodeInfo" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<!-- Define service endpoints -->
<wsdl:service name="MobileCodeWS">
<wsdl:port name="MobileCodeWSSoap" binding="tns:MobileCodeWSSoap">
<soap:address location="http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"/>
</wsdl:port>
</wsdl:service>
2.3、UDDI
UDDI(Universal Description, Discovery and Integration), General description 、 Discovery and integration services , Through it , Enterprises can register and collect Web Service. Enterprises will provide their own Web Service Registered in UDDI, You can also use other enterprises in UDDI register Web Service service , To achieve resource sharing .UDDI The aim is to bring the world's Web Service Sharing resources .
3、 The development of specification
3.1、JAX-WS
JAX-WS(Java API for XML-Based Web Service): A remote call can be converted to be based on XML agreement ( for example :SOAP agreement ), In the use of JAX-WS In the process , Developers do not need to use any code to write, generate, and process SAOP.JAX-WS The runtime will automatically set these API Call to SAOP News of the agreement .
On the server , adopt Java Language defines the interface needed for remote call (SEI:Service EndPoit Interface), And provide the related implementation , By calling JAX-WS To publish an interface, you can publish a Web Service service .
On the client side , adopt JAX-WS Of API To create a proxy to ( Replace the remote service object with the local proxy object ) Realize the call of remote server .
3.1、JAX-RS
JAX-RS(Java API for RESTful Web Services) yes JAVA EE6 A new technology introduced . It's a Java Application program interface of programming language , To support the transfer of according to a declarative state (Restful) Architectural style creation Web service .
4、 Application scenarios
4.1、 Advantages and disadvantages
Web Service The advantages of :
- The sending method is http Of post send out ,http The default port is 80, The firewall does not intercept by default 80, So cross the firewall ;
- use xml Format encapsulates data ,xml It's cross platform , Cross system .
Web Service shortcoming :
- use xml Format encapsulates data , So during the transmission , To transfer additional tags , With soap The continuous improvement of the agreement , The labels are getting bigger , Lead to webservice Performance degradation of .
4.2、 Applicable scenario
Web Service It's a SOA( Service oriented programming ) The architecture of , It is not dependent on language , It doesn't depend on the platform , It can realize the mutual call between different languages , adopt Internet Based on Http The interaction between network applications of the protocol . Apply to :
- Heterogeneous systems ( Different languages ) Integration of ;
- Integration of different clients , for example : browser 、 Move app、 Applet .
Two 、Web Service actual combat
be based on JAX-WS and JAX-RS There are many standardized framework implementations ,Apache CXF It's an open source Web Service frame ,CXF To simplify the Web Service Build and develop .
1、 be based on JAX-WS canonical Web Service structure
1.1、 Based on the original CXF Realization
1.1.1、 Server side
First step , establish maven project , introduce CXF Related coordinates :
<!--cxf Yes jaxws Support for -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.0.1</version>
</dependency>
<!-- built-in jetty web The server -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.0.1</version>
</dependency>
<!-- Rely on logs -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
</dependency>
The second step , Write entity class :
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 4005775933334039922L;
private Long id;
private String name;
private Integer age;
private Integer sex;
}
The third step , Write the service interface and implementation :
/** * @Des Define user services ( Server side ) * @Author jidi * @Email [email protected] * @WebService annotation : It means a Web Service service . */
@WebService(serviceName = "userService", portName="userPort")
public interface UserService {
/** * Save the user */
void saveUser(User user);
/** * Query all users */
List<User> getAllUsers();
/** * According to the user id Query the user */
User getUserById(Long id);
}
public class UserServiceImpl implements UserService {
@Override
public void saveUser(User user) {
System.out.println(" Save the user :" + user);
}
@Override
public List<User> getAllUsers() {
List<User> users = new ArrayList<>(6);
users.add(new User(1L, " base ", 25, 1));
users.add(new User(2L, " Huai Yong ", 24, 1));
users.add(new User(3L, "gala", 27, 0));
return users;
}
@Override
public User getUserById(Long id) {
return new User(3L, "gala", 27, 0);
}
}
Step four , Publishing services :
public class UserServicePublish {
public static void main(String[] args) {
// 1、 Create a factory object
JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
// 2、 Set parameters
// Client access address
factory.setAddress("http://localhost:8089/userService");
// Interface type
factory.setServiceClass(UserService.class);
// Interface implementation class
factory.setServiceBean(new UserServiceImpl());
// Set up interceptors
// Enter log interceptor ( Intercept client requests )
factory.getInInterceptors().add(new LoggingInInterceptor());
// Output log interceptor ( Intercept the server response )
factory.getOutInterceptors().add(new LoggingOutInterceptor());
// 3、 Publishing services
factory.create();
}
}
Step five , Browser access test , Enter the address :http://localhost:8089/userService?wsdl, Be able to access wsdl Description information , And there is no error on the console , Then the service is released successfully :
1.1.2、 Client
First step , establish maven project , introduce CXF Related coordinates ( Be consistent with the server );
The second step , Write client call :
public class UserServiceCall {
public static void main(String[] args) {
// 1、 Create a factory
JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
// 2、 Set parameters
// Set the service interface ( Reference the server interface )
proxyFactory.setServiceClass(UserService.class);
// Access address
proxyFactory.setAddress("http://localhost:8089/userService");
// 3、 Create an interface proxy object
UserService userService = (UserService) proxyFactory.create();
// Set up a log interceptor
Client client = ClientProxy.getClient(userService);
// Input interceptor ( Intercept server response )
client.getInInterceptors().add(new LoggingInInterceptor());
// Output interceptor ( Intercept client requests )
client.getOutInterceptors().add(new LoggingOutInterceptor());
// 4、 Call the server method
userService.saveUser(new User(1L, " base ", 25, 1));
List<User> users = userService.getAllUsers();
System.out.println(users);
}
}
1.2、Spring Integrate CXF Realization
1.2.1、 Server side
First step , Create based on maven Of web project , Import correlation dependency :
<!--cxf Yes jaxws Support for -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.0.1</version>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
The second step , Create entity class 、 Service interface and interface implementation class ( With native CXF Achieve consistency );
The third step , To write spring The configuration file , Publishing services :
<?xml version="1.0" encoding="UTF-8"?>
<!-- Introduce namespace ,jaxws yes CXF about JAX-WS Mode support -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd ">
<!-- Publishing services -->
<jaxws:server address="/userService" serviceClass="com.jidi.learn.ws.spring.web.UserService">
<!-- Service implementation class -->
<jaxws:serviceBean>
<bean class="com.jidi.learn.ws.spring.web.UserServiceImpl"/>
</jaxws:serviceBean>
<!-- Define input 、 Output interceptor -->
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
</jaxws:inInterceptors>
<jaxws:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
</jaxws:outInterceptors>
</jaxws:server>
</beans>
Step four , stay web.xml Configuration in file CXFServlet:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>cxf-ws-spring-server</display-name>
<!-- Appoint Spring Configuration file for -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Instantiation Spring Containers -->
<!-- When app starts , The listener is executed , It reads Spring Related configuration files , It defaults to WEB-INF Search for applicationContext.xml -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--CXF Framework core controller CXFServlet-->
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Step five , start-up web project , Through the address :http://localhost:8080/cxf-ws-spring-server/userService?wsdl, Access the service documentation .
1.2.2、 client
First step , Create based on maven Of web project , Import correlation dependency ;
The second step , To write spring The configuration file , Declare the service proxy object :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd ">
<!-- Create a service interface proxy object -->
<jaxws:client id="userService" address="http://localhost:8080/cxf-ws-spring-server/userService" serviceClass="com.jidi.learn.ws.spring.web.UserService">
<!-- Define input 、 Output interceptor -->
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
</jaxws:inInterceptors>
<jaxws:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
</jaxws:outInterceptors>
</jaxws:client>
</beans>
The third step , Write a test class to call the service :
public class UserServiceTest {
public static void main(String[] args) {
// 1、 Load profile , establish spring Containers
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2、 Get proxy object
UserService userService = (UserService)context.getBean("userService");
// 3、 Call service method
userService.saveUser(new User(123L, "jidi", 25,2));
}
}
1.3、Spring Boot Integrate CXF Realization
First step , establish maven project , Introduce dependency :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<!--cxf(ws Pattern )-->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.2.4</version>
</dependency>
The second step , Create entity class , Service interfaces and implementation classes ( ditto );
The third step , Write configuration classes , Publishing services :
/** * @Des Publishing services * @Author jidi * @Email [email protected] */
@Configuration
public class JaxWsConfig {
@Autowired
private Bus bus;
@Autowired
private UserService userService;
/** * wsdl The default access address is :http://127.0.0.1:8081/services/userService?wsdl * this bean You can use the default prefix services Change to a custom access prefix */
@Bean
public ServletRegistrationBean cxfServlet() {
return new ServletRegistrationBean(new CXFServlet(), "/ws/*");
}
/** * Publishing services */
@Bean
public Endpoint userService(){
Endpoint endpoint = new EndpointImpl(bus, userService);
endpoint.publish("/userService");
return endpoint;
}
}
Step four , Test whether the service is published successfully , You can access the service description file .
2、 be based on JAX-RS canonical Web Service structure
JAX-RS It's a Java Programming language interface , Designed to simplify use REST Architecture application development .JAX-RS API Use Java Programming language annotations to simplify RESTful web service Development of . Used by developers JAX-RS Annotation decoration of Java Class file of programming language to define resources and behaviors that can be applied to resources .JAX-RS The annotation of is the runtime annotation , Therefore, the runtime mapping will generate auxiliary classes and other auxiliary files for resources . contain JAX-RS Resource class Java EE Resources are configured in the application , Auxiliary classes and auxiliary files are generated , Resources are published to Java EE The server exposes it to the client .
2.1、 Based on the original CXF Realization
2.1.1、 Server side
First step , establish maven project , introduce CXF Related coordinates :
<!--cxf Yes jaxrs Support for -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.0.1</version>
</dependency>
<!-- built-in jetty web The server -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.0.1</version>
</dependency>
<!--json transformation -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.7</version>
</dependency>
The second step , Defining entity classes ( Need to add @XmlRootElement annotation ):
/** * @Des * @Author jidi * @Email [email protected] * annotation @XmlRootElement You can implement objects and xml Data conversion */
@XmlRootElement
public class Student implements Serializable {
private static final long serialVersionUID = -8981858391555915143L;
private Long id;
private String number;
private Long classNo;
private String name;
}
The third step , Define the service interface ( Use restful A note of style ) And implementation classes :
/** * @Des restful style , Service interface * @Author jidi * @Email [email protected] */
@Path("/")
public interface StudentService {
@POST
void saveStudent(Student student);
@PUT
void modifyStudent(Student student);
@DELETE
@Path("/{id}")
void deleteStudent(@PathParam("id") Long id);
@GET
@Path("/{id}")
Student getById(@PathParam("id") Long id);
/** * Specify the use of json Format return */
@GET
@Produces(MediaType.APPLICATION_JSON)
List<Student> getAllStudents();
}
public class StudentServiceImpl implements StudentService{
private static Map<Long, Student> map = new HashMap(8);
static {
map.put(1L, new Student(1L, "1000123", 1001L, " base "));
map.put(2L, new Student(2L, "1000111", 2001L, " Embrace "));
map.put(3L, new Student(3L, "1000222", 3001L, " Maomao "));
}
@Override
public void saveStudent(Student student) {
System.out.println(" Add students :" + student);
}
@Override
public void modifyStudent(Student student) {
System.out.println(" Modify students :" + student);
}
@Override
public void deleteStudent(Long id) {
System.out.println(" Delete students :" + id);
}
@Override
public Student getById(Long id) {
System.out.println(" According to id Query students ...");
return map.get(id);
}
@Override
public List<Student> getAllStudents() {
List<Student> list = new ArrayList(5);
for (Map.Entry<Long, Student> entry : map.entrySet()) {
System.out.println(entry.getValue());
list.add(entry.getValue());
}
System.out.println(" Check all student information ....");
return list;
}
}
Step four , Publishing services :
public class StudentServicePublish {
public static void main(String[] args) {
// 1、 Create a factory object
JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
// 2、 Set parameters
// Set access address
factory.setAddress("http://localhost:8888/rs/studentService");
// Set service interface implementation class
factory.setServiceBean(new StudentServiceImpl());
// Set up a log interceptor
factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
// Publishing services
factory.create();
}
}
Step five , adopt restful Style request , Call the service , Take querying all student information as an example , visit :http://localhost:8888/rs/studentService, You can see the response content :
2.1.2、 client
First step , establish maven factory , Import correlation dependency :
<!--restful Style client -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.0.1</version>
</dependency>
<!--json transformation -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.7</version>
</dependency>
The second step , Use restful The client invokes the service :
/** * @Des restuful style ,webservice Service release , Client test class * @Author jidi * @Email [email protected] */
public class StudentServiceTest {
/** * Test save */
@Test
public void add(){
WebClient.create("http://localhost:8888/rs/studentService")
.post(new Student(1L, "122312", 23L, "teswt"));
}
/** * Test modification */
@Test
public void modify(){
WebClient.create("http://localhost:8888/rs/studentService")
.put(new Student(1L, "122312", 23L, "teswt"));
}
/** * Test to delete */
@Test
public void delete(){
WebClient.create("http://localhost:8888/rs/studentService/1")
.delete();
}
/** * Test the query */
@Test
public void select(){
Student student = WebClient.create("http://localhost:8888/rs/studentService/"+1)
.get(Student.class);
System.out.println(student);
}
/** * Test the query ( Use json Format to receive the returned result ) */
@Test
public void selectAll(){
ArrayList<Student> list = (ArrayList<Student>)WebClient.create("http://localhost:8888/rs/studentService")
.accept(MediaType.APPLICATION_JSON)
.getCollection(Student.class);
System.out.println(list);
}
}
2.2、spring Integrate CXF Realization
2.2.1、 Server side
First step , Create based on maven Of web project , Import correlation dependency :
<!--cxf Yes jaxrs Support for -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.0.1</version>
</dependency>
<!--json transformation -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.7</version>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
The second step , Defining entity classes , Service interfaces and implementation classes ( ditto );
The third step , To write spring The configuration file , The release is based on restful Style of service :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd ">
<!-- Publishing interface -->
<jaxrs:server address="/studentService">
<jaxrs:serviceBeans>
<bean class="com.jidi.learn.rs.web.StudentServiceImpl"/>
</jaxrs:serviceBeans>
<!-- Define input 、 Output interceptor -->
<jaxrs:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
</jaxrs:inInterceptors>
<jaxrs:outInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
</jaxrs:outInterceptors>
</jaxrs:server>
</beans>
Step four , stay web.xml Configuration in file CXFServlet:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>cxf-rs-spring-server</display-name>
<!-- Appoint Spring Configuration file for -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Instantiation Spring Containers -->
<!-- When app starts , The listener is executed , It reads Spring Related configuration files , It defaults to WEB-INF Search for applicationContext.xml -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--webservice-->
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Step five , Start the application , Call the service , Take querying all student information as an example , visit :http://localhost:8080/cxf-rs-spring-server/studentService, You can see the response content :
2.2.2、 client
The client is the same as the native CXF The same as , It doesn't make any difference .
2.3、Spring Boot Integrate CXF Realization
First step , establish maven project , Introduce dependency :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<!--cxf(rs Pattern )-->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
<version>3.2.4</version>
</dependency>
<!--json transformation -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.7</version>
</dependency>
The second step , Create entity class , Service interfaces and implementation classes ( ditto );
The third step , Write configuration classes , Publishing services :
/** * @Des * @Author jidi * @Email [email protected] */
@Configuration
public class JaxRsConfig {
@Autowired
private Bus bus;
@Autowired
private StudentService studentService;
/** * this bean You can use the default prefix services Change to a custom access prefix */
@Bean
public ServletRegistrationBean cxfServlet() {
return new ServletRegistrationBean(new CXFServlet(), "/rs/*");
}
/** * Publishing services */
@Bean
public Server studentService(){
JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
factory.setBus(bus);
factory.setAddress("/student");
factory.setServiceBean(studentService);
return factory.create();
}
}
Step four , Test whether the service is published successfully .
3、 ... and 、 Call third-party services
stay Web Service Demonstrates the relationship between isomorphic systems , Publishing and invoking services , But it's actually used Web Service It is rare to implement calls between homogeneous systems , It is more about calling services published by third-party heterogeneous systems . here , The implementation details inside the third-party heterogeneous system are unknown , Only the relevant wsdl Description file , Need to pass through wsdl The description file implements the invocation of third-party services . Next, call the home address of the domestic mobile phone number to query WEB Service as an example , Explain the specific implementation process .
First step , download apache-cxf Release package :http://cxf.apache.org/download.html:
The second step , Unzip the distribution package , Set up CXF_HOME Variable , And add %CXF_HOME %/bin To path environment variable :
The third step ,CMD Command line input wsdl2java -help, A normal prompt indicates that the environment has been configured correctly :
Step four , adopt wsdl2java Generate webservice Client code , The order is as follows :
// -encoding Represents generated Java The file encoding format is utf8,
// -d Indicates that the code generation path is E:/test
// -all Indicates that the server and client are generated
wsdl2java -encoding utf-8 -d E:/test -all http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl
Step five , establish maven engineering , Copy all the generated code into the project , The package name uses its auto generated , The structure is as follows :
Step six , Based on the automatically generated client code , Implement your own business processing logic :
/** * @Des Domestic mobile phone number ownership inquiry WEB Service Testing * wsdl:http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl * @Author jidi * @Email [email protected] */
public class MobileTest {
@Test
public void test(){
// Create a service invocation client
MobileCodeWS ws = new MobileCodeWS();
// Get and call the service interface
MobileCodeWSSoap soap = ws.getMobileCodeWSSoap();
// Call the service through the interface
String info = soap.getMobileCodeInfo("15271833124", null);
// Processing logic
System.out.println(info);
}
}
边栏推荐
- Reroute the final chapter of riverpod in the state management of flutter
- 【 science, Technology, Business and management】 play Science and entrepreneurship: The Silicon Valley Saison 5 episodes 4 - 6
- 【代码注释】doxygen
- What's wrong with Android development today? Is the interview question I asked so difficult?
- openstack详解(十一)——openstack Glance服务理论知识
- LeetCode_ Simulation_ Medium_ 621. task scheduler
- MySQL basic database creation foundation
- How to draw a picture gracefully
- three.js学习笔记(十五)——着色器图案
- Redis集群实例内存使用率飙升排查
猜你喜欢

【科技、商业和管理】看剧学创业:《硅谷》第六季第3-5集

Countdown 3 days 𞓜 sofachannel 28 sofaark class isolation framework design

MSF针对FTP的后门攻击危害

倒计时 3 天 | SOFAChannel#28 SOFAArk 类隔离框架设计

Sword finger offer09-- implement queue with two stacks

three.js学习笔记(十五)——着色器图案

Redis集群实例内存使用率飙升排查

LeetCode_二叉树_前缀和_中等_437. 路径总和 III

Interviewer: how to open a video? What is second on video?

webservice服务调用
随机推荐
Basic pointer ~ guide you to the introduction pointer
【损失函数】focal loss损失函数解决样本不平衡问题
面试官:如何秒开视频?什么是秒开视频?
Que pensez - vous des architectures Multi - temps comme DAPR et layotto?
Paper understanding [RL - exp replay] - an equivalence between loss functions and non uniform sampling in exp replay
【概率论】变量之间的相关性计算
数据科学的道德与法规知识
Judge whether it is JSON or file stream
- Bean method ‘redisConnectionFactory‘ in ‘JedisConnectionConfiguration‘ not loaded because @Conditi
Minimum path sum
[linear algebra] understand eigenvalues and eigenvectors
Draw multiple polygons using canvas
webservice服务调用
MSF使用小技巧
Summary of Android development interview experience and compilation of actual records (must see)
pyqt5 pyside2
ERP 系统,编译和学习
【科技、商业和管理】看剧学创业:《硅谷》第六季第3-5集
倒计时 3 天 | SOFAChannel#28 SOFAArk 类隔离框架设计
How do you view the multi runtime architecture of dapr and layotto?