天天看点

JDK实现WebService(Java)

使用JDK实现WebService(Java)

一、环境介绍

IDE:IntelliJ IDEA 14.1
JDK:1.7
(-)使用@WebService注解方式
(-)使用Endpoint方式发布
(-)使用wsimport生成客户端
           

二、服务端

1.准备一个接口

package com.tgb.ws;

import javax.jws.WebService;

@WebService
public interface HelloWorld {
	String sayHi(String name);
}
           

2.完成接口的实现

package com.tgb.ws.impl;

import java.util.Date;
import javax.jws.WebService;
import com.tgb.ws.HelloWorld;

@WebService(endpointInter,
serviceName="HelloWorldWs")
public class HelloWorldWs implements HelloWorld {

	@Override
	public String sayHi(String name) {
		
		return name + ". Welcome!" + " Now time is "
		+ new Date();
	}

}
           

3.开始发布

package service;

import javax.xml.ws.Endpoint;

import com.tgb.ws.HelloWorld;
import com.tgb.ws.impl.HelloWorldWs;

public class ServerMain {

	public static void main(String[] args) {
		
		HelloWorld hw = new HelloWorldWs();
		
		// EndPoint publish WebService
		Endpoint.publish("http://localhost:8989/crazyit", hw);
		
		System.out.println("WebService is published!");
	}
}
           

4.验证是否发布成功

打开浏览器,输入地址:http://localhost:8989/crazyit
           

三、客户端

1.使用wsimport命令生成

- 创建一个Java工程
- 在src目录下进入cmd窗口(在地址栏打入cmd回车即可)
- 输入命令:wsimport -keep http://localhost:8989/crazyit?wsdl
           

2.开始调用服务

package client;

import com.tgb.ws.impl.HelloWorld;
import com.tgb.ws.impl.HelloWorldWs;

public class ClientMain {

	public static void main(String[] args) {
		HelloWorldWs hw = new HelloWorldWs();
		
		HelloWorld helloWorld = hw.getHelloWorldWsPort();
		
		System.out.println(helloWorld.sayHi("HelloWorld"));
		
	}
}
           

继续阅读