webservice快速入门-使用JAX-WS注解的方式快速搭建ws服务端和客户端(一)

WEBSERVICE快速入门的示例:

首先定义接口:

package com.whaty.platform.ws.server;

import javax.jws.WebService;

/**
 * @className:IMyservice.java
 * @Desc:定义:SEI service endpoint interface
 * @author:lizhuang
 * @createTime:2012-12-21 上午12:57:18
 */
//JAX-WS注解,表示java api xml for webservice。JDK自带API的XML格式的webservice
@WebService
public interface IMyservice {
	
	int add(int a, int b);

	int minus(int a, int b);
}

其次编写实现类:

package com.whaty.platform.ws.server;

import javax.jws.WebService;

/** 
 * @className:MyServiceImpl.java
 * @Desc:定义:SIB service implemention bean
 * @author:lizhuang
 * @createTime:2012-12-21 上午01:01:22
 */
//endpointInterface指定接入点接口:接口必须存在
@WebService(endpointInterface="com.whaty.platform.ws.server.IMyservice")
public class MyServiceImpl implements IMyservice {

	public int add(int a, int b) {
		System.out.println("a+b="+(a+b));
		return a+b;
	}

	public int minus(int a, int b) {
		System.out.println("a-b="+(a-b));
		return a-b;
	}

}

最后发布我们的服务,直接右键运行main方法,如果控制台没报错,多半是发布成功了,否则检查你的代码:

package com.whaty.platform.ws.server;

import javax.xml.ws.Endpoint;

/**
 * @className:MyServer.java
 * @Desc:发布服务
 * @author:lizhuang
 * @createTime:2012-12-21 上午01:02:39
 */
public class MyServer {
	public static void main(String[] args) {
		//访问方式:http://localhost:7777/tudou?wsdl
		String address="http://localhost:7777/tudou";
		Endpoint.publish(address, new MyServiceImpl());
	}
}


浏览器地址栏输入:访问webservice看看是否发布成功【地址后面加上"?wsdl"】:

http://localhost:7777/tudou?wsdl


浏览器显示如下:

This XML file does not appear to have any style information associated with it. The document tree is shown below.


























































下面我们创建客户端访问:

package com.whaty.platform.ws.client;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.whaty.platform.ws.server.IMyservice;

/**
 * @className:MyClient.java
 * @Desc:访问发布的服务
 * @author:lizhuang
 * @createTime:2012-12-21 上午01:23:57
 */
public class MyClient {
	public static void main(String[] args) {

		try {
			//服务WSDL Document的地址
			URL url = new URL("http://localhost:7777/tudou?wsdl");
			//Qnameqname是qualified name 的简写
			//2.构成:由名字空间(namespace)前缀(prefix)以及冒号(:),还有一个元素名称构成
			//由发布的wsdl可知namespace为http://server.ws.platform.whaty.com/,
			QName qname=new QName("http://server.ws.platform.whaty.com/","MyServiceImplService");
			Service service=Service.create(url, qname);
			IMyservice ms=service.getPort(IMyservice.class);
			ms.add(1, 4);
			ms.minus(1, 4);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
}


控制台打印如下:

a+b=5
a-b=-3

你可能感兴趣的:(EJB/WS/RMI,webservice快速入门)