下面是一个简单的Java WebService实例,使用了JAX-WS标准:
- 编写WebService接口:
import javax.jws.WebMethod; import javax.jws.WebService; @WebService public interface HelloWorld { @WebMethod String sayHello(String name); }
- 实现WebService接口:
import javax.jws.WebService; @WebService(endpointInterface = "HelloWorld") public class HelloWorldImpl implements HelloWorld { @Override public String sayHello(String name) { return "Hello, " + name + "!"; } }
- 配置Web Service部署描述文件(web.xml):
WebServiceExample WebServiceExample com.sun.xml.ws.transport.http.servlet.WSServlet com.sun.xml.ws.transport.http.servlet.WSServletContextListener 1 WebServiceExample /hello
- 配置Web Service绑定描述文件(sun-jaxws.xml):
- 使用JAX-WS提供的工具生成Web Service服务端和客户端代码:
wsimport -keep -p com.example.ws http://localhost:8080/WebServiceExample/hello?wsdl
-
部署到Servlet容器(如Tomcat)并启动。
-
测试WebService服务端:
在浏览器中访问http://localhost:8080/WebServiceExample/hello?wsdl
,能够看到生成的WSDL文件。
- 测试WebService客户端:
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接口的方法与服务端进行交互。