下面是一個簡單的Java WebService實例,使用了JAX-WS標準:
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface HelloWorld {
@WebMethod
String sayHello(String name);
}
import javax.jws.WebService;
@WebService(endpointInterface = "HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Override
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
<web-app>
<display-name>WebServiceExample</display-name>
<servlet>
<servlet-name>WebServiceExample</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<init-param>
<param-name>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</param-name>
<param-value>1</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>WebServiceExample</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version="2.0">
<endpoint name="HelloWorld" implementation="HelloWorldImpl"
url-pattern="/hello"/>
</endpoints>
wsimport -keep -p com.example.ws http://localhost:8080/WebServiceExample/hello?wsdl
部署到Servlet容器(如Tomcat)并啟動。
測試WebService服務(wù)端:
在瀏覽器中訪問http://localhost:8080/WebServiceExample/hello?wsdl
,能夠看到生成的WSDL文件。
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實例演示了一個簡單的問候服務(wù)。通過WebService接口定義了一個sayHello
方法,實現(xiàn)類返回一個問候語??蛻舳送ㄟ^調(diào)用WebService接口的方法與服務(wù)端進行交互。