webservice使用的主要目标是实现跨平台的可互操作行。初入门的小例子:
package com.you.webservice;
import javax.jws.WebService;
@WebService
public interface Myservice {
public int add(int a, int b);
public int minus(int a, int b);
}
这个接口是供服务器发布出去的接口,一定注意接口上面要表明@webservice。
package com.you.webservice;
import javax.jws.WebService;
@WebService (endpointInterface="com.you.webservice.Myservice")
public class MyserviceImpl implements Myservice{
@Override
public int add(int a, int b) {
System.out.println("a" + "+" + "b" + "=" + (a+b));
return (a+b);
}
@Override
public int minus(int a, int b) {
System.out.println("a" + "-" + "b" + "=" + (a-b));
return (a-b);
}
}
这是接口的实现类,同样也被服务器发布出去,这个类上面也需要注解,并且要指明指向的接口。可通过在浏览器中输入http://localhost:8000/ns?wsdl看到提供的服务。
package com.you.webservice;
import javax.xml.ws.Endpoint;
public class Myserver {
public static void main(String[] args) {
String address = "http://localhost:8000/ns";
Endpoint.publish(address, new MyserviceImpl());
}
}
服务器端将服务发布出去,指明访问的地址和发布实现接口的类。
package com.you.webservice;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class TestClient {
public static void main(String[] args) {
try{
URL url = new URL("http://localhost:8000/ns?wsdl");
QName qname = new QName("http://webservice.you.com/", "MyserviceImplService");
Service service = Service.create(url, qname);
Myservice ms = service.getPort(Myservice.class);
System.out.println(ms.add(12, 33));
}catch(Exception e) {
throw new RuntimeException(e);
}
}
}
客户端类,通过地址访问服务器发布的类。