利用jdk开发web service简单实例

来源:互联网 发布:瓶中小人真理对话知乎 编辑:程序博客网 时间:2024/05/31 13:15

eclipse新建一个java project

1. 编写SEI接口

package com.yf.day01_ws.ws;


import javax.jws.WebMethod;
import javax.jws.WebService;

/**
File: HelloWS.java
Description: SEI
@author 
@date 2016年10月24日 下午4:14:28
@version 1.0 
**/

@WebService
public interface HelloWS {

@WebMethod
public String sayHello(String name);

}


2. 编写SEI接口实现类

package com.yf.day01_ws.ws;

import javax.jws.WebService;

/**
File: HelloWSImpl.java
Description: SEI的实现
@author 
@date 2016年10月25日 下午2:32:21
@version 1.0 
**/

@WebService
public class HelloWSImpl implements HelloWS {

@Override
public String sayHello(String name) {
        System.out.println(" server sayHello() " + name);
return "Hello " + name;
}

}


3. 编写web service启动

package com.yf.day01_ws.ws.server;

import javax.xml.ws.Endpoint;

import com.yf.day01_ws.ws.HelloWSImpl;

/**
File: ServerTest.java
Description: 发布web service
@author
@date 2016年10月25日 下午2:39:34
@version 1.0 
**/


public class ServerTest {

public static void main(String[] args) {

String address = "http://192.168.31.172:8989/day01_ws/hellows";
Endpoint.publish(address, new HelloWSImpl());
System.out.println("web服务发布成功!");
}
}

运行后,server启动成功


4. eclipse上测试web service

wsdl地址: http://192.168.31.172:8989/day01_ws/hellows?wsdl

启动web service explorer,输入地址 http://192.168.31.172:8989/day01_ws/hellows?wsdl 查看



5. 用代码测试web service

eclipse新建java project

cmd命令进入这个project的src目录,然后运行:

wsimport -keep http://192.168.31.172:8989/day01_ws/hellows?wsdl

运行无误后会在src目录下生成接口代码,列表如下:



新建测试类,代码如下:

package com.yf.day01_ws_client.test;

import com.yf.day01_ws.ws.HelloWSImpl;
import com.yf.day01_ws.ws.HelloWSImplService;

/**
File: ClientTest.java
Description: TODO
@author 
@date 2016年10月25日 下午2:59:48
@version 1.0 
**/

public class ClientTest {

public static void main(String[] args) {
HelloWSImplService factory = new HelloWSImplService();
HelloWSImpl helloWS = factory.getHelloWSImplPort();
System.out.println(helloWS.getClass());

String result = helloWS.sayHello("wuyifeng");
System.out.println("client " + result);
}
}


也可以将http://192.168.31.172:8989/day01_ws/hellows?wsdl,页面内容保存到本地wsdl文件,然后用命令

wsimport -keep C:\WorkSpace\day01_ws_client2\hellows.wsdl

运行完成后也可以生成相应接口代码.



0 0
原创粉丝点击