新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

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

发布时间:2023-08-18 07:59:55

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

下面是一个简单的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
version="2.0">
url-pattern="/hello"/>

```
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接口的方法与服务端进行交互。