摘要:本文首要介绍了SpringBoot搭建WebService服务的服务端开发,和WebService的客户端开发,让不熟悉WebService开发的同学能够快速入门。

WebService服务端开发

pom.xml

引进首要的maven jar

<dependencies>
    <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>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
        <version>3.3.4</version>
        <exclusions>
            <exclusion>
                <groupId>javax.validation</groupId>
                <artifactId>validation-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

提早界说一个UserDto目标

@Data
public class UserDto {
    private Long id;
    private String userName;
    private Boolean active;
}

声明服务接口

@WebService(name = HelloService.SERVICE_NAME,targetNamespace = HelloService.TARGET_NAMESPACE)
public interface HelloService {
    /** 露出服务称号 */
    String SERVICE_NAME = "HelloService";
    /** 命名空间,一般是接口的包名倒序 */
    String TARGET_NAMESPACE = "http://hello.server.webservice.huzhihui.com";
    @WebMethod
    @WebResult(name = "String")
    String hi(@WebParam(name = "userName") String userName);
    @WebMethod
    @WebResult(name = "UserDto")
    List<UserDto> activeUsers(@WebParam(name = "userDtos") List<UserDto> userDtos);
}
  • @WebParam

该注解标识传入的参数称号,必须要写name参数,否则生成的wsdl参数称号是args1 args2 argsn

  • @WebResult

该注解标识回来的成果,必须加name参数,否则生成的wsdl回来参数是return

界说接口完成

@WebService(
        /** 和接口的服务称号保持一致 */
        serviceName = HelloService.SERVICE_NAME,
        /** 和接口的命名空间保持一致 */
        targetNamespace = HelloService.TARGET_NAMESPACE,
        /** 接口全途径 */
        endpointInterface = "com.huzhihui.webservice.server.hello.HelloService"
)
@BindingType(value = "http://www.w3.org/2003/05/soap/bindings/HTTP/")
@Component
public class HelloServiceImpl implements HelloService {
    @Override
    public String hi(String userName) {
        return "hi " + userName;
    }
    @Override
    public List<UserDto> activeUsers(List<UserDto> userDtos) {
        for (UserDto userDto : userDtos) {
            userDto.setActive(Boolean.TRUE);
        }
        return userDtos;
    }
}

注解WebService服务

@Configuration
public class HelloEndpointConfig {
    @Autowired
    private Bus bus;
    @Autowired
    private HelloService helloService;
    @Bean
    public Endpoint helloEndpoint(){
        EndpointImpl endpoint = new EndpointImpl(bus,helloService);
        endpoint.publish("/helloService");
        return endpoint;
    }
}

注意

如果有多个WebService接口则按照上面的过程多写几个接口就行了。

发动服务端

拜访wsdl发布的接口

地址是http://localhost:8080/services/helloService?wsdl; 如果新增了其他WebService服务接口地址是你装备的endpoint.publish("/xxxx"); http://localhost:8080/services/xxxx?wsdl

SpringBoot WebService服务端和客户端使用案例

客户端开发

java调用WebService一般有三种办法;

  • 生成客户端代码拜访
  • JaxWsDynamicClientFactory动态拜访
  • HttpClient直接发送xml报文拜访(最原始的办法)

我接下来将依次供给事例来拜访

提早装备pom.xml

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
    <version>3.3.4</version>
    <exclusions>
        <exclusion>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

生成客户端代码拜访

idea插件装置

SpringBoot WebService服务端和客户端使用案例

运用插件生成代码

插件最好运用jdk8或许jdk6环境,其他jdk版别可能会报错。

SpringBoot WebService服务端和客户端使用案例

SpringBoot WebService服务端和客户端使用案例

运用客户端代码

在我们装备的包下面会生成一个helloService.wsdl文件,我一般是修改了生成的HelloService_service中的wsdl文件地址为本地途径,

SpringBoot WebService服务端和客户端使用案例

改为了如下装备

SpringBoot WebService服务端和客户端使用案例

SpringBoot WebService服务端和客户端使用案例

我加上了@Component就能在Spring中运用了

SpringBoot WebService服务端和客户端使用案例

拜访该地址就能拜访到接口了

JaxWsDynamicClientFactory动态拜访

该形式是最精简的拜访形式,只不过要求能看到wsdl文件恳求参数和回来参数的结构界说,这里不详细说结构了,自己百度

一般数据类型拜访事例

如果恳求参数和回来参数都是java的基础数据类型,运用如下代码即可

public static void hi() throws Exception{
    JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
    Client client = dcf.createClient("http://localhost:8080/services/helloService?wsdl");
    Object[] objects = client.invoke("hi","zhangsan");//hi办法名 后边是可变参数
    //输出调用成果
    System.out.println(objects[0].getClass());
    System.out.println(objects[0].toString());
}

拜访成果

SpringBoot WebService服务端和客户端使用案例

数据结构拜访事例

我们需要把用到的数据目标界说在WebServicetargetNamespace反过来的包下面,然后再来调用接口,

public static void activeUsers() throws Exception{
    JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
    Client client = dcf.createClient("http://localhost:8080/services/helloService?wsdl");
    List<Object> userDtos = new ArrayList<>();
    UserDto userDto = new UserDto();
    userDto.setId(1L);
    userDto.setUserName("zs");
    userDtos.add(userDto);
    Object[] objects = client.invoke("activeUsers",userDtos);//list3办法名 后边是可变参数
    //输出调用成果
    System.out.println(objects[0].getClass());
    System.out.println(objects[0].toString());
}

上面的事例用到了UserDto类,我就界说如下(注意包名)

package com.huzhihui.webservice.server.hello;
import lombok.Data;
@Data
public class UserDto {
    private Long id;
    private String userName;
    private Boolean active;
}

成果如下

SpringBoot WebService服务端和客户端使用案例

HttpClient直接发送xml报文拜访

public static void restTemplateActiveUsers(){
        RestTemplate restTemplate = new RestTemplate();
        long start = System.currentTimeMillis();
//<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:hel="http://hello.server.webservice.huzhihui.com">
//   <soap:Header/>
//   <soap:Body>
//      <hel:activeUsers>
//         <!--Zero or more repetitions:-->
//         <userDtos>
//            <!--Optional:-->
//            <active></active>
//            <!--Optional:-->
//            <id>1</id>
//            <!--Optional:-->
//            <userName>hzh</userName>
//         </userDtos>
//      </hel:activeUsers>
//   </soap:Body>
//</soap:Envelope>
        //结构webservice恳求参数
        StringBuffer soapRequestData = new StringBuffer();
        soapRequestData.append("<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:hel="http://hello.server.webservice.huzhihui.com">");
        soapRequestData.append("<soap:Header/>");
        soapRequestData.append("<soap:Body>");
        soapRequestData.append("<hel:activeUsers>");
        soapRequestData.append("<userDtos>");
        soapRequestData.append("<active></active>");
        soapRequestData.append("<id>1</id>");
        soapRequestData.append("<userName>hzh</userName>");
        soapRequestData.append("</userDtos>");
        soapRequestData.append("</hel:activeUsers>");
        soapRequestData.append("</soap:Body>");
        soapRequestData.append("</soap:Envelope>");
        //结构http恳求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("text/xml;charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<String> formEntity = new HttpEntity<>(soapRequestData.toString(), headers);
        //回来成果
        String resultStr = restTemplate.postForObject("http://localhost:8080/services/helloService?wsdl", formEntity, String.class);
        System.out.println(resultStr);
    }

成果如下

SpringBoot WebService服务端和客户端使用案例

至于xmljava目标,工具很多,自己随便找找就有了,我项目中运用的是jackson xml

xml转目标

  • 界说的DTO
@Data
@JacksonXmlRootElement(localName = "soap:Envelope")
public class EnvelopeDto {
    @JacksonXmlProperty(localName = "soap:Body")
    private BodyDto bodyDto;
    @JacksonXmlProperty(localName = "xmlns:soap",isAttribute = true)
    private String xmlnsSoap;
}
@Data
@JacksonXmlRootElement(localName = "soap:Body")
public class BodyDto {
    @JacksonXmlElementWrapper(localName = "ns2:activeUsersResponse")
    @JacksonXmlProperty(localName = "UserDto")
    private List<UserDto> userDtos;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@JacksonXmlRootElement(localName = "UserDto")
public class UserDto {
    @JacksonXmlProperty(localName = "id")
    private Long id;
    @JacksonXmlProperty(localName = "userName")
    private String userName;
    @JacksonXmlProperty(localName = "active")
    private Boolean active;
}
  • 测验办法
@Test
void xmlToObj() throws Exception{
    String value = "<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><soap:Body><ns2:activeUsersResponse xmlns:ns2="http://hello.server.webservice.huzhihui.com"><UserDto><active>true</active><id>1</id><userName>hzh</userName></UserDto><UserDto><active>true</active><id>2</id><userName>zs</userName></UserDto></ns2:activeUsersResponse></soap:Body></soap:Envelope>\n";
    XMLInputFactory input = new WstxInputFactory();
    input.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    XmlMapper xmlMapper = new XmlMapper(new XmlFactory(input,new WstxOutputFactory()));
    EnvelopeDto envelopeDto = xmlMapper.readValue(value,EnvelopeDto.class);
    System.out.println(envelopeDto);
}
  • 测验成果

SpringBoot WebService服务端和客户端使用案例