Java WebService 简单实例(附实例代码)

2023-10-18 1302阅读

下面是一个简单的Java WebService实例,使用了JAX-WS标准:
1. 编写WebService接口:
java
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface HelloWorld {
@WebMethod
String sayHello(String name);
}

2. 实现WebService接口:
java
import javax.jws.WebService;
@WebService(endpointInterface = "HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Override
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}

3. 配置Web Service部署描述文件(web.xml):
xml

WebServiceExample

WebServiceExample
com.sun.xml.ws.transport.http.servlet.WSServlet

com.sun.xml.ws.transport.http.servlet.WSServletContextListener
1



WebServiceExample
/hello



4. 配置Web Service绑定描述文件(sun-jaxws.xml):
xml




5. 使用JAX-WS提供的工具生成Web Service服务端和客户端代码:

wsimport -keep -p com.example.ws http://localhost:8080/WebServiceExample/hello?wsdl

6. 部署到Servlet容器(如Tomcat)并启动。
7. 测试WebService服务端:
在浏览器中访问http://localhost:8080/WebServiceExample/hello?wsdl,能够看到生成的WSDL文件。
8. 测试WebService客户端:
java
import com.example.ws.HelloWorld;
import com.example.ws.HelloWorldImplService;
public class HelloWorldClient {
public static void main(String[] args) {
HelloWorldImplService service = new HelloWorldImplService();
HelloWorld port = service.getHelloWorldImplPort();
String result = port.sayHello("Alice");
System.out.println(result);
}
}

这个简单的Java WebService实例演示了一个简单的问候服务。通过WebService接口定义了一个sayHello方法,实现类返回一个问候语。客户端通过调用WebService接口的方法与服务端进行交互。

Java WebService 简单实例(附实例代码)
(图片来源网络,侵删)

VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]