SpringBoot integrates WebService (server + client)

SpringBoot integrates WebService (server + client)

Article catalogue

1, Server

This project integrates WebService through SpringBoot+Mybatis to realize the functions of the server receiving the data from the client and writing it into the database,

1. Project structure

2. Import Maven dependency after creating SpringBoot project

Just replace it all with mine

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- web starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- webService-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>


        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-core</artifactId>
            <version>3.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

    </dependencies>

3. Create a pojo package to store the entity class User

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class User {

    private Integer id;
    private String userId;
    private String userName;
   
}

4. Create a service package to store service classes

UserService

package cn.edu.usts.sbmpservice.service;

import cn.edu.usts.sbmpservice.pojo.User;

import javax.jws.WebParam;
import javax.jws.WebService;
import java.text.ParseException;

@WebService(name = "UserService", // Exposed service name
        targetNamespace = "http://service.sbmpservice.usts.edu.cn "/ / namespace, which is generally the reverse order of the package name of the interface
)
public interface UserService {

    int addUser(User user);
    User queryUser(Integer id);

}

UserServiceImpl interface implementation class

package cn.edu.usts.sbmpservice.service.impl;


import cn.edu.usts.sbmpservice.dao.UserDao;
import cn.edu.usts.sbmpservice.dao.YljgjxcDao;
import cn.edu.usts.sbmpservice.pojo.User;
import cn.edu.usts.sbmpservice.pojo.Yljgjxc;
import cn.edu.usts.sbmpservice.service.UserService;
import cn.edu.usts.sbmpservice.utils.util;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jws.WebService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//@Component
@WebService(serviceName = "UserService", // Consistent with the name specified in the interface
        targetNamespace = "http://service.sbmpservice.usts.edu.cn ", / / consistent with the namespace in the interface, generally the package name of the interface is inverted
        endpointInterface = "cn.edu.usts.sbmpservice.service.UserService"// Interface address
)
public class UserServiceImpl implements UserService {

        @Autowired
        private UserDao userDao;

        @Override
        public int addUser(User user ){

            System.out.println("addUser");

            return userDao.addUser(user);
        }
        @Override
        public User queryUser(Integer id){
            System.out.println("queryUser"+" "+id);
            User user = userDao.queryUser(id);
            System.out.println(user);
            return userDao.queryUser(id);
        }

}

5. Build a dao floor

UserDao processing data

package cn.edu.usts.sbmpservice.dao;

import cn.edu.usts.sbmpservice.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface UserDao {
    int addUser(User user);
    User queryUser(Integer id);

}

6. Create a mapper folder under the resources directory

UserDao.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.edu.usts.sbmpservice.dao.UserDao">
    <insert id="addUser" parameterType="User">
        insert into user.user(userId,userName) values (#{userId},#{userName})
    </insert>

    <select id="queryUser" resultType="User">
        select * from user.user where userId = #{userId}
    </select>

</mapper>

7. Configuration database

Change the suffix of the application file to yml format, and then configure the database and port number according to your own situation

mybatis:
  type-aliases-package: cn.edu.usts.sbmpservice.pojo
  mapper-locations: classpath:mapper/*.xml
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8


server:
  port: 8081

8. Configure and publish WebService (top priority)

Create a new config directory to store configuration files

startclass.java

package cn.edu.usts.sbmpservice.config;

import cn.edu.usts.sbmpservice.service.UserService;
import cn.edu.usts.sbmpservice.service.impl.UserServiceImpl;
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.xml.ws.Endpoint;

@Configuration
public class StartClas {

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

    @Bean(name = "wsBean")
    public ServletRegistrationBean dispatcherServlet() {
        ServletRegistrationBean wbsServlet = new ServletRegistrationBean(new CXFServlet(), "/ws/*");
        return wbsServlet;
    }

    @Bean
    public UserService userService() {
        return new UserServiceImpl();
    }

    @Bean
    public Endpoint endpointPurchase(SpringBus springBus, UserService userService) {
        EndpointImpl endpoint = new EndpointImpl(springBus(), userService());
        endpoint.publish("/api");
        System.out.println("Service published successfully! The address is: http://localhost:8081/ws/api?wsdl");
        return endpoint;


    }
}

9. Publish WebService services

The service is published successfully. Open the browser and enter the address

The content shown in the figure indicates that the service is published successfully. The image content is WSDL (Web Services Description Language), which is used to describe Web services and how to access them. Next, you can write the client.

2, Client

There are many methods for the client to call the WebService interface. Only two methods are shown here, and the first is recommended

1.service programming call mode

1.1 directory structure

You need to synchronize the pojo and service files of the server to the client

1.2 call WebService

package cn.edu.usts;

import cn.edu.usts.pojo.User;
import cn.edu.usts.service.UserService;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.MalformedURLException;
import java.net.URL;

public class Client {
    public static void main(String[] args) throws MalformedURLException {
        System.setProperty("javax.xml.bind.JAXBContext", "com.sun.xml.internal.bind.v2.ContextFactory");
        //URL to create WSDL
        URL url = new URL("http://localhost:8080/ws/api?wsdl");
        // Specify namespace and service name
        QName qName = new QName("http://service.sbmpservice.usts.edu.cn", "UserService");
        Service service = Service.create(url, qName);
        // Return the specified interface through the getPort method
        UserService myServer = service.getPort(UserService.class);  // Method 1
//        UserService myServer = service. getPort(new QName(" http://serviceImpl.service.usts.edu.cn/ "," userserviceimplport "), userservice.class); / / method 2

        // Call the method to get the return value
        User user1 = new User(2,"tom");
        myServer.addUser(user1);
        User user = myServer.queryUser(2);
        System.out.println(user.toString());
    }

}

compile

The client is shown in the figure. The data is inserted successfully, the query is successful, and the web Service interface is called successfully

The server is shown in the figure. Successfully received the data sent by the client and wrote it to the database

The database is as shown in the figure, and the data is successfully inserted

2. Use WSDL to generate local client code to call WebService

This method is simple to use, but some key elements are written into the generated code during code generation, which is inconvenient to maintain, so it is only used for testing.

2.1 generate local client code

Create a new project and directly generate the client code in the project (there is no need to generate and copy it elsewhere)

Open the terminal

Enter the src/main/java/... Directory and use the wsimport command to generate the client code

 wsimport -keep -extension http://localhost:8080/ws/api?wsdl

Press enter, and then you can see the generated client code in the directory

2.2 call WebService service

public class app {
    public static void main(String[] args) {

        //Create an object for the service access point collection
        UserService_Service has = new UserService_Service();
        //Get service implementation class
        //Get the bound service class according to the binding object of the service access point in the collection of service access points
        UserService soap = has.getUserServiceImplPort();

        //Invoke service
        User user = soap.queryUser(2);
        System.out.println(user.toString());

    }
}

3, Problems and Solutions

1.Exception in thread "main" com.sun.xml.internal.ws.fault.ServerSOAPFaultException

When using service programming to call the interface, an error is reported. According to the information on the Internet, it is said that the internal jar version of webservice conflicts with the jar of jdk currently used. It is necessary to set the system properties and add them to the code

System.setProperty("javax.xml.bind.JAXBContext", "com.sun.xml.internal.bind.v2.ContextFactory");

2.A query was run and no Result Maps were found for the Mapped Statement

Reason: the resultType attribute was forgotten to be specified in the mapper on the server

Tags: Android Interview Back-end Front-end

Posted by Mikedean on Tue, 02 Aug 2022 22:15:14 +0530