Understand WebService in one article

1, Basic concepts

(1) What is Web?

  web (World Wide Web) is the global wide area network, also known as the world wide web. It is a global, dynamic interactive and cross platform distributed graphic information system based on hypertext and HTTP. It is a network service based on the Internet. It provides a graphical and easy to access intuitive interface for browsers to find and browse information on the Internet. The documents and hyperlinks organize the information nodes on the Internet into an interrelated network structure.

Since a service is a service, it must be who serves who. In the network, it generally refers to the caller of the service (the requesting client) and the provider of the service (the responding server).
  web services are client and server applications that communicate through the world wide web (WWW) Hypertext Transfer Protocol (HTTP). As described by the World Wide Web Consortium (W3C), web services provide a standard method for interoperability between software applications running on various platforms and frameworks.
  Web services can be seen as on-demand code. Just as we call functions and methods, Web services can be seen as calling functions or methods over the Internet using some protocol and some protocol.
   a Web service is a function or method that can be called by sending an HTTP request to a URL with parameters, and then the service returns the result as a response.

The biggest advantage of Web services is that it is platform independent.

  considering the above figure, we can see that applications written in Java can interact with PHP and. net platforms through web services. Therefore, it is completely platform independent. Web Services exposed by PHP can be used by any platform, whether Java,. net or PHP. This capability of Web services makes it so popular. Therefore, web service is a language independent communication method.

(2) Http?

agreement?

1. Composition of the request:

Request line
 Request header
 Request body

2. Composition of response?

Response status line: response code response status
 Response header
 Response body: page file before browser parsing

3. Request process?

(3) Schema?

Constraints?
standard?
What labels do they have?
How to introduce Schema constraints?

2, Introduction to WebService

(1) What is WebService?

The cross platform and cross language remote call technology is suitable for data interaction and data transmission in different systems and languages

  1. Based on Web server,..
  2. A specification
  3. A solution to cross platform traffic

(2) Why use WebService?

Web Service can meet the requirements of application integration, software reuse, cross firewall communication and so on. Different business requirements are different.
The details are as follows:
(1) Cross firewall communication
(2) Application system integration (3) software and data reuse. In short, if a function needs to be used by multiple systems, you can use web service to develop a server interface for different client applications. It is mainly used in the interface call between enterprise internal systems and public network oriented web service service.

(3) When to use web service?

advantage:
a) Interoperability of heterogeneous platforms in theory, the biggest advantage of Web Service is to provide seamless Street connection technical means of heterogeneous platforms. Because different users use different hardware platforms, different operating platforms, different operating systems, different software and different protocols for communication, there is a need for mutual communication. Web Service enables any two applications to communicate with each other as long as they can read and write XML.
b) More extensive software reuse (for example, mobile Taobao can reuse the business logic of Taobao). Software reuse technology can greatly improve the production efficiency and quality of software by combining existing modules to build applications. As long as the user obtains the WSDL file describing the Web Service, he can easily generate the client proxy and access the Web Service through the proxy.
c) With low cost, strong readability and wide application range, Web Service can represent data and call requests with XML based SOAP. And transmit data in XML format through HTTP protocol
d) Fast software distribution mode (each Web Service is called a producer. Different producers can cooperate with each other to complete the whole application) Web Service will completely change the software distribution mode. The software supplier can decompose the software into a system composed of Web Service modules and publish it directly on the Web.
e) The most important point is that the client and server may be developed in different languages. However, through the service interface provided by web service, the client and server can pass objects before.

Disadvantages: because soap is based on xml transmission, using xml transmission will transmit some irrelevant content, which will affect the efficiency. With the improvement of soap protocol, soap protocol adds a lot of content, which leads to more information carried by using soap to complete simple data transmission, and the efficiency will be affected again;
As a standard technology for web cross platform access, many companies restrict the use of Web Service, but if it is a simple interface, you can directly use http to transmit custom data format, which makes development faster.

  1. Different languages
  2. Different companies
  3. Different servers

The WebServer response is: HTLM + XML
So XML parsing has to see!

(4) Important concepts of WebService:

1. WSDL specification

Web Service description language WSDL (SebService Definition Language) is a formal description document provided in a language that can be read by the machine, and a language based on XML (a subset under the standard General Markup Language) is used to describe Web Service and its functions, parameters and return values. Because it is based on XML, WSDL is both machine readable and human readable.
wsdl specification,
1) Through the wsdl specification, you can describe the services published by the web service server;
2) wsdl specification is based on xml file and describes the whole service in xml language;
3) The wsdl description describes: service name (class) interface method name (method) interface parameter (method parameter) data type returned by the service (method return value)

  • wsdl:types: the input parameters and return values of a method in the interface defined in Java
  • wsdl:message: Abstract typed definition of data structure of communication message. The relationship between method and message is one to two (one is the input of method and the other is the output of method)
  • wsdl:portType = interface
  • wsdl:operation = method defined in the interface
  • wsdl:binding: binding of specific protocol and data format specification for a specific port type
  • wsdl:service: it is responsible for assigning the network communication address to a specific binding


2. SOAP Protocol

SOAP = based on HTTP + XML data
   SOAP is the simple object access protocol, which is a lightweight protocol for exchanging XML (a subset of Standard General Markup Language) encoded information.
SOAP, as a protocol based on XML language, is used to transmit data on the Internet. SOAP can run on any other transmission protocol.

Composition of SOAP:

  1. Required Envelope – this xml document can be identified as a SAOAP message.
  2. Optional Headers – contains header information.
  3. Required body – the body section contains the method of the server to be executed and the data sent to the server (including call and response information).
  4. Optional Fault – provides information about the error that occurred while processing this message.

3. SEI

Is the suffix of Service interface class + Service, and Service is automatically appended. As shown in the figure:

4. UDDI

How Web Service providers publish their Web services to the Internet requires the use of UDDI. UDDI is a cross industry and cross platform open architecture that can help Web Service providers publish Web Service information on the Internet. UDDI is a directory service. Enterprises can register and search Web services through UDDI. In simple terms, UDDI is a directory, but it stores some information about Web services. UDDI communicates through SOAP and is built on. Net. UDDI is Universal Description, discovery and integration, that is, Universal Description, discovery and integration. The purpose of UDDI is to establish standards for e-commerce; UDDI is a set of implementation standards for Web-based, distributed, information registry provided for Web services. At the same time, it also includes a set of implementation standards for access protocols that enable enterprises to register their own Web services so that other enterprises can discover.

5. SOA thinking

SOA (Service-Oriented Architecture) is an idea that connects different functional units of applications through neutral contracts (independent of hardware platform, operating system and programming language), so as to better integrate various forms of functional units. At present, WebService is a better implementer of SOA. WebService uses HTTP as the transmission protocol and SOAP (Simple Object Access Protocol) as the format of transmission message. However, WebService does not fully conform to the concept of SOA, because SOAP protocol is a unique protocol of WebService and does not meet the requirements of SOA transmission protocol transparency. SOAP is an application protocol, which was used in the early implementation of RPC. The transmission protocol can rely on HTTP, SMTP and so on.

The emergence of SOA has gone through the following processes:

Generally, the system using SOA is called service BUS (BUS), and the structure is shown in the following figure:

*The front is conceptual theory, and the following is the code practice part.*

3, Practice

(1) JAXB

JAXB = Java Api for Xml Binding

1. Introduction

   JAXB is the abbreviation of Java Architecture for XML Binding, which provides a shortcut to convert Java objects into XML.
   JAXB can realize the mutual conversion between POJO objects and XML. The Unmarshaller class can deserialize XML data into Java POJO objects, and selectively validate XML data during disaggregation; Marshall class is the process of serializing Java POJO objects into XML data.

2. Examples

  • Book POJO object

  • JaxbTest
package com.wind.jaxb;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

/**
 * JAXB Sample Demo
 *
 * @author Wind
 */
public class JaxbTest {

    public static void myMarshaller() throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // format
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");  // Set encoding

        marshaller.marshal(new Book(11, "Douluo continent", 33.8), System.out);

    }

    public static void myUnMarshaller() throws JAXBException {
        String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><book><bookName>Douluo continent</bookName><id>11</id><price>33.8</price></book>";

        JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        Book book = (Book) unmarshaller.unmarshal(new StringReader(xmlString));
        System.out.println(book);
    }

    public static void main(String[] args) throws JAXBException {
        myMarshaller();
        System.out.println();
        System.out.println("---------------------------------");
        myUnMarshaller();
    }
}

(2) WSDL to Java code generation

How does the client code and call after the server is developed? Is it troublesome to write all by hand?

1. JDK lib package

2. CXF bin

(1) Open cmd and move the directory to the bin directory of ApacheCXF

(2) Copy the wsdl document address using the command: wsdl 2java

D:\DevSoft\ApacheCXF\apache-cxf-3.4.4\bin>wsdl2java http://localhost:8001/cxf/server?wsdl

(3) Copy the generated folder to the java folder of the project

(4) Write test

package com.wind.test;

import com.wind.cxf.HelloWorld;
import com.wind.cxf.HelloWorldImplService;

/**
 * Test the Java client code generated from WSDL
 *
 * @author Wind
 */
public class WsdlToJavaTest {

    public static void main(String[] args) {
        HelloWorld helloWorld = new HelloWorldImplService().getHelloWorldImplPort();
        String result = helloWorld.sayHello("zhang wuji", 18);
        System.out.println(result); // CXF 	 sayHello: it's impossible 	 18 ??? Why is it garbled

        // The solution to calling Chinese garbled code for the Java client code generated above:
        // Add coding settings during generation: D: \ devsoft \ apachecxf \ apache-cxf-3.4.4 \ bin > wsdl2java - encoding UTF-8 http://localhost:8001/cxf/server?wsdl
    }
}

(5) Delete useless code and make it into jar package

It's too troublesome to type a jar package with a separate file in the IDEA. I gave up~
Use Eclipse to create jar packages:
1) Select the. java file to be printed as a jar package
2) Right click - > export - > java - JAR file - > Next

(3) CXF development

1. Introduction to mainstream WebService framework

(1)Axis1/Axis2(✖)

Axis (APACHE extensible interaction system) Apache extensible interaction system is an open source WebService running engine, which is essentially a SOAP engine, providing the basic framework for creating server-side, client-side and gateway SOAP operations.
   axis is divided into 1.x series and 2.x series. The architecture and application of the two series are quite different. Axis1.x is relatively more stable and complete.

(2)XFire(✖)

  XFire is the next generation of Java SOAP framework. XFire provides very convenient API s that can be used to develop service-oriented (SOA) programs. It supports various standards and has excellent performance (based on the low memory STAX model).

(3)CXF(✔)

Apache CXF = Celtix + XFire
  Apache CXF, formerly known as Apache CeltiXfire, has been officially renamed Apache CXF, or CXF for short. CXF inherits the essence of Celtix and XFire's two major open source projects, provides comprehensive support for JAX-WS, and provides a variety of Binding, DataBinding, Transport and Format support. It can easily achieve the release and use of the Binding according to the needs of the actual project, using code priority (Code First) or person WSDL priority (Code). Apache CXF is already a formal Apache top-level project.

2. CXF implements WebService under Jax WS specification [jar package version]

(1) Add jar package for construction

1) Create a dynamic Web project

Creating dynamic Web project reference with IntelliJ IDEA

2) Add jar package

Download address

(2) Build HelloWorld service interface (@ WebService annotation added)

package com.wind.cxf;

import javax.jws.WebService;

/**
 * Interface for external leakage
 *
 * @author Wind
 * @date 2021-10-28 02:25:34
 */
@WebService
public interface HelloWorld {

    /**
     * Test method sayHello
     *
     * @param name full name
     * @param age  Age
     * @return
     */
    String sayHello(String name, int age);
}

(3) Create helloworldiimpl service implementation class

package com.wind.cxf;

/**
 * Interface implementation class
 *
 * @author Wind
 * @date 2021-10-28 02:25:56
 */
public class HelloWorldImpl implements HelloWorld {

    @Override
    public String sayHello(String name, int age) {
        System.out.println("sss");
        return "CXF\tsayHello:" + name + "\t" + age;
    }

}

(4) Create the MainServer service startup class (JaxWsServerFactoryBean)

package com.wind.cxf;

import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

/**
 * WebService Service startup class
 *
 * @author Wind
 * @date 2021-10-28 02:24:51
 */
public class MainServer {

    public static void main(String[] args) {

        JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();

        factoryBean.setAddress("http://localhost:8001/cxf/server");
        factoryBean.setServiceClass(HelloWorldImpl.class);

        Server server = factoryBean.create();
        server.start();
    }

}

(5) There are two test access methods:

1) Call directly through Eclipse tools



2) Write the test code ClientTest to call the exposed service (JaxWsProxyFactoryBean)
package com.wind.cxf;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

/**
 * Write the test code ClientTest to call the exposed service (JaxWsProxyFactoryBean)
 *
 * @author Wind
 * @date 2021-10-28 02:24:01
 */
public class ClientTest {

    public static void main(String[] args) {

        JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();

        factoryBean.setAddress("http://localhost:8001/cxf/server");
        factoryBean.setServiceClass(HelloWorld.class);

        HelloWorld helloWorld = (HelloWorld) factoryBean.create();
        String result = helloWorld.sayHello("Zhang San", 23);

        System.out.println("*************" + result);
    }

}

3. CXF implements WebService under Jax WS specification [Maven version]

(1) Server

1) Create project

2) Add cxf dependency
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wind</groupId>
    <artifactId>01_jaxws_server</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>01_jaxws_server</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- To carry out jaxws Service development -->
        <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>

        <!-- Log implementation -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
3) Write service interface
package com.wind.service;

import javax.jws.WebService;

/**
 * WebService Interface
 *
 * @author Wind
 * @date 2021-10-29 18:07:18
 */
@WebService
public interface UserService {

    /**
     * Sample Demo
     *
     * @param name full name
     * @return
     */
    String sayHi(String name);

}
4) Write service interface implementation
package com.wind.service.impl;

import com.wind.service.UserService;

/**
 * WebService Interface implementation class
 *
 * @author Wind
 * @date 2021-10-29 18:10:43
 */
public class UserServiceImpl implements UserService {

    @Override
    public String sayHi(String name) {
        return name + "Say Hello";
    }
}
5) Publishing services
package com.wind.publish;

import com.wind.service.impl.UserServiceImpl;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

/**
 * Server publishing service
 *
 * @author Windy
 * @date 2021-10-29 18:16:15
 */
public class Server {

    public static void main(String[] args) {
        // Service Factory
        JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
        // Set service address
        factory.setAddress("http://localhost:8000/user");
        // Set service class
        factory.setServiceBean(new UserServiceImpl());
        // Publishing services
        factory.create();
        // Tips
        System.out.println("Server start");
    }

}
6) Accessing wsdl specification

(2) Client

1) Create project, add Maven dependency

Consistent with the server project dependency

2) Write service interface

It is also consistent with the server interface

package com.wind.service;

import javax.jws.WebService;

/**
 * WebService Interface
 *
 * @author Wind
 * @date 2021-10-29 18:07:18
 */
@WebService
public interface UserService {

    /**
     * Sample Demo
     *
     * @param name full name
     * @return
     */
    String sayHi(String name);

}
3) Remote access server
package com.wind.test;

import com.wind.service.UserService;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

/**
 * Client remote service call
 *
 * @author Windy
 * @date 2021-10-29 18:58:21
 */
public class Client {

    public static void main(String[] args) {
        // Server interface access address: http://localhost:8000/user?wsdl

        // 1. Create cxf proxy project object
        JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
        // 2. Set the remote access server address
        factoryBean.setAddress("http://localhost:8000/user "); / / pass the interface address or interface wsdl document address
        // 3. Set interface type
        factoryBean.setServiceClass(UserService.class);
        // 4. Generate proxy object for interface
        UserService userService = factoryBean.create(UserService.class);

        // Proxy object type: [Java proxy is divided into: 1. Static proxy 2. Dynamic proxy (jdk interface proxy {proxy @}, CGLB subclass proxy {CGLB @})]
        System.out.println(userService);   // org.apache.cxf.jaxws.JaxWsClientProxy@2e222612

        // 5. Remote access
        String result = userService.sayHi("Wang Zhaojun");
        System.out.println(result);
    }

}

(3) Add a log interceptor to observe the SOAP protocol content

1) Add log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log # Log generation directory
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
2) Add log interceptor on the server
package com.wind.publish;

import com.wind.service.impl.UserServiceImpl;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

/**
 * Server publishing service
 *
 * @author Windy
 * @date 2021-10-29 18:16:15
 */
public class Server {

    public static void main(String[] args) {
        // 1. Service Factory
        JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
        // 2. Set service address
        factory.setAddress("http://localhost:8000/user");
        // 3. Set service class
        factory.setServiceBean(new UserServiceImpl());

        // Add log input and output interceptors to observe the contents of SOAP request and SOAP response
        factory.getInInterceptors().add(new LoggingInInterceptor());
        factory.getOutInterceptors().add(new LoggingOutInterceptor());

        // 4. Publishing services
        factory.create();
        // Tips
        System.out.println("Server start");
    }

}
3) Response content
2021-10-29 19:44:39,278 27370  [tp1297502382-22] INFO  serServiceImplPort.UserService  - Inbound Message
----------------------------
ID: 1
Address: http://localhost:8000/user
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml; charset=UTF-8
Headers: {Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[191], content-type=[text/xml; charset=UTF-8], Host=[localhost:8000], Pragma=[no-cache], SOAPAction=[""], User-Agent=[Apache CXF 3.0.1]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHi xmlns:ns2=" http://service.wind.com/ "> < arg0 > Wang Zhaojun < / arg0 > < / NS2: sayhi > < / soap: body > < / soap: envelope >
--------------------------------------
2021-10-29 19:44:39,440 27532  [tp1297502382-22] INFO  serServiceImplPort.UserService  - Outbound Message
---------------------------
ID: 1
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml
Headers: {}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHiResponse xmlns:ns2=" http://service.wind.com/ "> < return > Wang Zhaojun 	 Say Hello</return></ns2:sayHiResponse></soap:Body></soap:Envelope>
--------------------------------------

4. Spring integrates CXF to realize WebService under Jax WS specification [spring version]

(1) Server

1) Create Web projects, add dependencies

2) Add dependency
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wind</groupId>
    <artifactId>03_jaxws_spring_server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>03_jaxws_spring_server Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- CXF WS development  -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.0.1</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
            <!-- function tomcat7 method: tomcat7:run -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <!-- Specify port -->
                    <port>8080</port>
                    <!-- Request path -->
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
3) Configuring CXF servlet and Spring container with web.xml
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!--1.spring Container configuration-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--2. cxfsevlet to configure-->
    <!--
        webservice On the server side, the publishing service needs to be configured CXFServlet,Configured here servlet Path, the most part of the final service path:
        Service access path: http://localhost:8080/web.xml configuration path / path configured in spring configuration file
    -->
    <servlet>
        <servlet-name>cxfservlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>cxfservlet</servlet-name>
        <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>

</web-app>
4) Service interface and service implementation

Same as directory:

    1. / (1) / 3)
    1. / (1) / 4)

5) Add the Spring configuration file applicationContext.xml
<?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:cxf="http://cxf.apache.org/core"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       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/core
        http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd
        http://cxf.apache.org/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd">

    <!--
        Spring integration cxf Publishing services, key points:
        1. Service address
        2. Service class
        Service full access address: http://localhost:8080/ws/hello
    -->
    <jaxws:server address="/hello">
        <jaxws:serviceBean>
            <bean class="com.wind.service.impl.UserServiceImpl"/>
        </jaxws:serviceBean>
    </jaxws:server>

</beans>
6) Start Tomcat for the pom.xml plug-in

7) Accessing test wsdl documents

http://localhost:8080/ws/hello?wsdl

(2) Client

1) Create project

Either java project or Java Web can be used

2) Copy interface to project

3) Create the Spring configuration file applicationContext.xml and configure the service interface type
<?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:cxf="http://cxf.apache.org/core"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       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/core
        http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd
        http://cxf.apache.org/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd">

    <!--
        Spring integration cxf Client configuration:
            1. Service address     http://localhost:8080/ws/hello
            2. Service interface type, by Spring Generate proxy object
    -->
    <jaxws:client
            id="helloService"
            serviceClass="com.wind.service.UserService"
            address="http://localhost:8080/ws/hello">
    </jaxws:client>

</beans>
4) Junit test
package com.wind.test;

import com.wind.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Client {

    // Injection object
    @Resource
    private UserService userService;

    @Test
    public void remote(){
        // View the proxy object type of the interface class com.sun.proxy.$Proxy45
        System.out.println(userService.getClass());

        // Remote access server method
        System.out.println(userService.sayHi("LV Fengxian"));
    }

}

5. CXF implements WebService under Jax RS specification [Maven version]

Based on the Http application layer, xml data or json data can be transmitted. By default, xml data is requested

(1) Server

1) Create project

2) Add dependency
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wind</groupId>
    <artifactId>05_jaxrs_server</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>05_jaxrs_server</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- To carry out jaxrs Service development -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http-jetty</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-client</artifactId>
            <version>3.0.1</version>
        </dependency>

        <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>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
3) Create entity classes passed between WebService server and client

User

package com.wind.entity;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

/**
 *  Based on restful web service, the communication between client and server can transfer xml data and json data
 *  @XmlRootElement Specifies the name of the root node when the object is serialized to xml or json data
 *  xml:
 *       <User>
 *           <id></id>
 *           <username></username>
 *           <city></city>
 *       </User>
 *   json:
 *   {"User":  {"id":100,  "username":"jack","city":"Guangzhou "}}
 *
 * @author Windy
 */
@XmlRootElement(name = "User")
public class User {
    private Integer id;
    private String username;
    private String city;

    private List<Car> cars = new ArrayList<Car>();

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public List<Car> getCars() {
        return cars;
    }

    public void setCars(List<Car> cars) {
        this.cars = cars;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", city=" + city + ", cars=" + cars + "]";
    }

}

Car

package com.wind.entity;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Car")
public class Car {
    private Integer id;
    private String carName;
    private Double price;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCarName() {
        return carName;
    }

    public void setCarName(String carName) {
        this.carName = carName;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car [id=" + id + ", carName=" + carName + ", price=" + price + "]";
    }

}
4) Write service interface
package com.wind.service;

import com.wind.entity.User;

import javax.ws.rs.*;
import java.util.List;


/**
 * Service interface class
 *
 * @author Wind
 */
@Path("/userService")   //  Access the path corresponding to the current service interface [similar to @ ResquesMapping annotation]
@Produces("*/*")  // Returned data format types supported by the server[*/* representative xml and json Yes, the default is xml]
public interface IUserService {

    /**
     * Indicates the type of request processed. post corresponds to the insert operation
     *
     * @param user
     */
    @POST
    @Path("/user") // Access the path corresponding to the current service interface method. [... / userService/user]
    @Consumes({"application/xml", "application/json"}) //  The requested data format type supported by the server
    void saveUser(User user);

    /**
     * Indicates the type of request processed. put corresponds to the update modification operation
     *
     * @param user
     */
    @PUT
    @Path("/user")
    @Consumes({"application/xml", "application/json"})
    void updateUser(User user);

    /**
     * Indicates the type of request processed. get corresponds to query modification
     *
     * @return
     */
    @GET
    @Path("/user")
    @Produces({"application/xml", "application/json"}) // Returned data format types supported by the server
    List<User> findAllUsers();

    /**
     * Indicates the type of request processed. get corresponds to query modification
     *
     * @param id
     * @return
     */
    @GET
    @Path("/user/{id}")
    @Consumes("application/xml")
    @Produces({"application/xml", "application/json"})
    User finUserById(@PathParam("id") Integer id);

    /**
     * Indicates the type of request processed. Delete corresponds to the delete operation
     *
     * @param id
     */
    @DELETE
    @Path("/user/{id}")
    @Consumes({"application/xml", "application/json"})
    void deleteUser(@PathParam("id") Integer id);
}
5) Write a service interface implementation class
package com.wind.service.impl;

import com.wind.entity.Car;
import com.wind.entity.User;
import com.wind.service.IUserService;

import java.util.ArrayList;
import java.util.List;

/**
 * Service interface implementation class
 *
 * @author Wind
 */
public class UserServiceImpl implements IUserService {

    @Override
    public void saveUser(User user) {
        System.out.println("save user:" + user);
    }

    @Override
    public void updateUser(User user) {
        System.out.println("update user:" + user);
    }

    @Override
    public List<User> findAllUsers() {
        List<User> users = new ArrayList<User>();
        User user1 = new User();
        user1.setId(1);
        user1.setUsername("Xiao Ming");
        user1.setCity("Beijing");

        List<Car> carList1 = new ArrayList<Car>();
        Car car1 = new Car();
        car1.setId(101);
        car1.setCarName("Porsche");
        car1.setPrice(1000000d);
        carList1.add(car1);
        Car car2 = new Car();
        car2.setId(102);
        car2.setCarName("bmw");
        car2.setPrice(400000d);
        carList1.add(car2);
        user1.setCars(carList1);

        users.add(user1);

        User user2 = new User();
        user2.setId(2);
        user2.setUsername("Xiao Li");
        user2.setCity("Shanghai");
        users.add(user2);

        return users;
    }

    @Override
    public User finUserById(Integer id) {
        if (id == 1) {
            User user1 = new User();
            user1.setId(1);
            user1.setUsername("Xiao Ming");
            user1.setCity("Beijing");
            return user1;
        }
        return null;
    }

    @Override
    public void deleteUser(Integer id) {
        System.out.println("delete user id :" + id);
    }

}
6) Publishing services
package com.wind.publish;

import com.wind.service.impl.UserServiceImpl;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;

public class Server {
    public static void main(String[] args) {
        // Create a factory for publishing services
        JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();

        // Set service address
        factory.setAddress("http://Localhost: 8001 / WS / "); / / call the service on demand. The final address is: http://localhost:8001/ws/ @ Path of interface / @ Path of interface method

        // Set service class
        factory.setServiceBean(new UserServiceImpl());

        // Add log I / O interceptor
        factory.getInInterceptors().add(new LoggingInInterceptor());
        factory.getOutInterceptors().add(new LoggingOutInterceptor());

        // Publishing services
        factory.create();

        System.out.println("Publishing service succeeded, port 8001");
    }
}
7) Accessing wsdl specification

(2) Client

Jax RS has fewer service interfaces than Jax WS

1) Create project

Create a Java project

2) Add dependency

Copy server pom.xml dependency

3) Data copy entity class to be encapsulated

4) The test calls the server remotely through the WebClient object
package com.wind.test;

import com.wind.entity.User;
import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.Test;

import javax.ws.rs.core.MediaType;

public class Client {

    @Test
    public void testSave() {
        User user = new User();
        user.setId(100);
        user.setUsername("Jerry");
        user.setCity("gz");
        // Call the server remotely through the WebClient object
        WebClient
                .create("http://localhost:8001/ws/userService/user ") / / specify the server address
                .type(MediaType.APPLICATION_JSON)  // Specify the request data format (xml, json)
                .post(user);    // Specify the request type [. post()/put()/delete()/get()]
    }

    @Test
    public void testGet() {
        // Query a
        User user =
                WebClient
                        .create("http://localhost:8001/ws/userService/user/1")
                        .accept(MediaType.APPLICATION_JSON)  // Specify the response data format
                        .get(User.class);
        System.out.println(user);
    }
}

6. Spring integrated CXF+Restful WebService development under Jax RS [spring version]

(1) Server

1) Create a Web project

2) Add Spring, CXF RT frontend jaxrs dependencies
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wind</groupId>
    <artifactId>07_jaxrs_spring_server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>07_jaxrs_spring_server Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- cxf conduct rs Development must be imported  -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>3.0.1</version>
        </dependency>
        <!-- Log import  -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>

        <!-- client -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-client</artifactId>
            <version>3.0.1</version>
        </dependency>

        <!-- extend json Provider -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-extension-providers</artifactId>
            <version>3.0.1</version>
        </dependency>

        <!-- transformation json Kit, by extension providers rely on -->
        <dependency>
            <groupId>org.codehaus.jettison</groupId>
            <artifactId>jettison</artifactId>
            <version>1.3.7</version>
        </dependency>

        <!-- spring core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <!-- spring web integrate -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <!-- spring integration junit  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <!-- junit Development package -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
            <!-- function tomcat7 method: tomcat7:run -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <!-- Specify port -->
                    <port>8080</port>
                    <!-- Request path -->
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
3) Configure web.xml
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!--1.spring Container configuration-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--2. cxfsevlet to configure-->
    <!--
        webservice On the server side, the publishing service needs to be configured CXFServlet,Configured here servlet Path, the most part of the final service path:
        Service access path: http://localhost:8080/web.xml configuration path / spring configuration path
    -->
    <servlet>
        <servlet-name>cxfservlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>cxfservlet</servlet-name>
        <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>

</web-app>
4) Create entity classes, service interfaces and interface implementation classes passed between WebService server and client

Copy above

6) The Spring configuration file applicationContext.xml publishes services through the configuration file
<?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:cxf="http://cxf.apache.org/core"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       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/core
        http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd
        http://cxf.apache.org/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd">

    <!--
        Spring integration cxf Publish based on restful Style service, key points:
        1. Service address
        2. Service class
        Service full access address:
            http://localhost:8080/ws/hello
    -->
    <jaxrs:server address="/userService">
        <jaxrs:serviceBeans>
            <bean class="com.wind.service.impl.UserServiceImpl"/>
        </jaxrs:serviceBeans>
    </jaxrs:server>

</beans>
7) Start project

(2) Client

1) Create project

Java Project

2) Add dependency

Replication server dependency

3) Create entity class

Copy server entity

4) Testing
package com.wind.test;

import com.wind.entity.User;
import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.Test;

import javax.ws.rs.core.MediaType;

public class Client {

    @Test
    public void testSave() {
        User user = new User();
        user.setId(100);
        user.setUsername("Jerry");
        user.setCity("gz");
        // Call the server remotely through the WebClient object
        WebClient
                // Description Url: http://IP Address: port / web.xml configured address / applicationContext.xml configured address / interface @ Path address / method @ Path address in the interface
                .create("http://localhost:8080/ws/userService/userService/user")
                .type(MediaType.APPLICATION_JSON)  // Specifies that the requested data format is json
                .post(user);
    }

    @Test
    public void testGet() {
        // Query a
        User user =
                WebClient
                        .create("http://localhost:8080/ws/userService/userService/user/1")
                        .accept(MediaType.APPLICATION_JSON)
                        .get(User.class);
        System.out.println(user);
    }
}

4, Summary

(1) Logic

In addition to project creation, dependency addition and basic configuration, common code:

Server[ JaxWsServerFactoryBean]: Write entity, interface and interface implementation class
 Client[ JaxWsProxyFactoryBean]  : Write entity and call

It's this~

(2) @ notes

@WebService
@WebMethod
@WebResult
@WebParam
@XmlRootElement
@Path
@Produces
@Consumes

IDEA calls WebService?
Does IDEA generate WebService server code?
Listen for requests?

jetty?

Keywords: Java intellij-idea webservice

Added by ppowell on Sat, 30 Oct 2021 10:49:18 +0300