jax-ws入门篇

1.定义服务接口
package com.sha;

import javax.jws.WebMethod;
import javax.jws.WebService;
/**
 * @author: Administrator
 * Date: 2015-4-17
 * Time: 上午09:04:30
 */
@WebService(
		name="hello"
)
public interface IHello {
	/**
	 * sayHello
	 * @param arg0
	 * @return
	 */
	@WebMethod
	public String sayHello(String arg0);
}

2.实现接口
package com.sha;

import javax.jws.WebService;
/**
 * @author: Administrator
 * Date: 2015-4-17
 * Time: 上午09:04:30
 */
@WebService(
		endpointInterface = "com.sha.IHello", 
		portName = "hello_Port", 
		serviceName = "hello_Service", 
		targetNamespace = "http://www.sha.com/hello"
)
public class HelloImpl implements IHello{

	@Override
	public String sayHello(String arg0)
	{
		System.out.println("客户端调用 sayHello ");
		return "hello "+arg0;
	}

}


3.发布服务
package com.sha;

import javax.xml.ws.Endpoint;
/**
 * 启动服务
 * @author: Administrator
 * Date: 2015-4-17
 * Time: 上午09:04:30
 */
public class HelloServer {
	private static String ENDPOINT_URL="http://localhost:31038/hello";

	public static void main(String[] args)
	{
		IHello helloimpl = new HelloImpl();
		Endpoint endpoint = Endpoint.create(helloimpl);
		/*发布webservice*/
		endpoint.publish(ENDPOINT_URL);
		System.out.println("运行并发布hello WebService Successfully...");
	}
	
}

4.客户端访问
package com.sha;

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

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
/**
 * 客户端
 * @author: Administrator
 * Date: 2015-4-17
 * Time: 上午09:04:30
 */
public class HelloClient {
	private static final String ENDPOINT_URL = "http://localhost:31038/hello?wsdl";
	private static final String nameSpace = "http://www.sha.com/hello";
	private static final String serviceName = "hello_Service";


	public static void main(String[] args) throws MalformedURLException
	{
		//连接服务器端
		URL url = new URL(ENDPOINT_URL);
		QName name = new QName(nameSpace, serviceName);
		Service service = Service.create(url, name);
		IHello hello = service.getPort(IHello.class);
		String response = hello.sayHello("admin");
		System.out.println("返回的报文:" + response);
	}
}

5.build.xml生成相应的wsdl文件和xsd文件
<project default="wsgen">
	<!--wsgen
		-cp 定义classpath 
		-r 生成 bean的wsdl文件的存放目录
		-s 生成发布Web Service的源代码文件的存放目录(如果方法有抛出异常,则会生成该异常的描述类源文件)
		-d 生成发布Web Service的编译过的二进制类文件的存放目录(该异常的描述类的class文件) 
		-->
	<target name="wsgen">
		<exec executable="wsgen">
			<arg line="-cp ./server/classes -keep -s ./server -d ./server/classes -r ./public -wsdl com.sha.HelloImpl" />
		</exec>
	</target>

</project>

你可能感兴趣的:(webservice,jax-ws)