如何发布webservice java
使用JAX-WS发布WebService
在Java中发布WebService可以使用JAX-WS(Java API for XML Web Services)技术。以下是具体实现步骤:
创建服务端点接口(SEI)
import javax.jws.WebService;
@WebService
public interface HelloWorld {
String sayHello(String name);
}
实现服务端点接口
import javax.jws.WebService;
@WebService(endpointInterface = "com.example.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
发布WebService
import javax.xml.ws.Endpoint;
public class WebServicePublisher {
public static void main(String[] args) {
String url = "http://localhost:8080/hello";
Endpoint.publish(url, new HelloWorldImpl());
System.out.println("WebService published at: " + url);
}
}
使用Spring Boot发布WebService
对于现代Java应用,使用Spring Boot发布WebService更加简便:
添加依赖到pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
创建服务类
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
@Endpoint
public class CountryEndpoint {
private static final String NAMESPACE_URI = "http://example.com/webservice";
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest")
@ResponsePayload
public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) {
GetCountryResponse response = new GetCountryResponse();
// 实现业务逻辑
return response;
}
}
配置WebService
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
@EnableWs
@Configuration
public class WebServiceConfig {
@Bean
public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(ApplicationContext context) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(context);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean<>(servlet, "/ws/*");
}
}
生成WSDL文件
对于需要提供WSDL描述的情况:
使用JAX-WS自动生成
Endpoint.publish("http://localhost:8080/hello?wsdl", new HelloWorldImpl());
使用Spring WS生成
<bean id="countries" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
<property name="schema" ref="schema"/>
<property name="portTypeName" value="Countries"/>
<property name="locationUri" value="/ws"/>
<property name="targetNamespace" value="http://example.com/webservice"/>
</bean>
测试WebService
发布后可以通过SOAP客户端测试服务:
使用cURL测试
curl --header "content-type: text/xml" -d @request.xml http://localhost:8080/ws
使用SOAPUI工具创建新项目并输入WSDL地址进行测试。







