摘要:本文主要介绍了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
客户端开发
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插件安装
使用插件生成代码
插件最好使用jdk8或者jdk6的环境,其他jdk版本可能会报错。
使用客户端代码
在我们配置的包下面会生成一个helloService.wsdl文件,我一般是修改了生成的HelloService_service中的wsdl文件地址为本地路径,
改为了如下配置
我加上了@Component就能在Spring中使用了
访问该地址就能访问到接口了
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());
}
访问结果
数据结构访问案例
我们需要把用到的数据对象定义在WebService的targetNamespace反过来的包下面,然后再来调用接口,
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;
}
结果如下
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);
}
结果如下
至于xml转java对象,工具很多,自己随便找找就有了,我项目中使用的是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);
}