天天看點

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"));
		
	}
}
           

繼續閱讀