使用JDK实现WebService(Web)
一、环境介绍
IDE:IntelliJ IDEA 14.1
JDK:1.7
Tomcat:8.0.35
(-)使用@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(endpointInterface="com.tgb.ws.HelloWorld",
serviceName="HelloWorldWs")
public class HelloWorldWs implements HelloWorld {
@Override
public String sayHi(String name) {
return name + ". Welcome!" + " Now time is "
+ new Date();
}
}
3.开始发布
package servlet;
import com.tgb.ws.HelloWorld;
import com.tgb.ws.impl.HelloWorldWs;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.xml.ws.Endpoint;
@WebServlet(value="",loadOnStartup=0)
public class ServerMainServlet extends HttpServlet {
public void init() throws ServletException {
HelloWorld hw = new HelloWorldWs();
// EndPoint publish WebService
Endpoint.publish("http://localhost:8989/crazyit", hw);
System.out.println("WebService is published!");
}
}
4.验证是否发布成功
配置tomcat,启动项目
打开浏览器,输入地址: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"));
}
}