注 : 该篇主要介绍如何使用 Jaxws 创建webservice, 如欲了解 CXF 或 AXIS, 请移步CXF创建webservice 或 AXIS 创建webservice.
#1. 创建接口和实现
@WebService public interface IService { @WebMethod public String login(String name,String pwd); } @WebService(endpointInter) public class ServiceImpl implements IService{ @Override public String login(String name, String pwd) { if(name.equals("111111") && pwd.equals("222222")){ return "登录成功"; }else{ return "用户名或密码错误"; } } }
#2. 发布服务
执行上述操作后, 访问 http://localhost:8080/ws/IService?wsdl , 如果有出现类似 xml 的文件内容则表示发布成功!public class ServiceRun { public static void main(String[] args) { String url = "http://localhost:8080/ws/IService"; Endpoint.publish(url, new ServiceImpl()); System.out.println("发布成功,使用 http://localhost:8080/ws/IService?wsdl 进行访问!"); } }
#3. 调用 (本地调用/远程调用)
a. 本地调用public class ServiceClient { public static void main(String[] args) throws Exception { //该命名空间取生成的xml文件中targetNamespace="http://ws/",也可通过@WebService注解种的属性指定 String namespaceUrl = "http://ws/"; //创建访问wsdl文件的URL URL url = new URL(" http://localhost:8080/ws/IService?wsdl"); //使用命名空间和服务名(取xml文件中service name="ServiceImplService")来创建QName,服务名可通过@WebService注解种的属性指定 QName qName = new QName(namespaceUrl, "ServiceImplService"); //使用URL,QName创建服务 Service service = Service.create(url,qName); //根据接口原类获取本地接口 IService ser = service.getPort(IService.class); //调用接口方法 System.out.println(ser.login("222222", "111111")); System.out.println(ser.login("111111", "222222")); } }
b. 远程调用
使用JDK自带的 wsimport 命令 或 wsgen 命令.