java 创建WebSservice

本文介绍了一个简单的 Java WebService 示例,包括服务端的搭建与发布过程,以及客户端如何通过 wsimport 指令生成调用代码,并提供了一个具体的调用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一,服务端

</pre><pre name="code" class="java">package webservice;

import pool.ThreadPool;

import javax.xml.ws.Endpoint;

/**
 * Created by Juxuny on 2014/9/24.
 */


public class Main {

    public static void main(String[] args) {
        System.out.println("start service.");
        Endpoint.publish("http://localhost:8888/hello", new MyHello());
    }

}

package webservice;

import javax.jws.WebService;

/**
 * Created by Juxuny on 2014/9/24.
 */
@WebService(endpointInterface = "webservice.HelloWorld")
public class MyHello implements HelloWorld {

    /**
     *
     * @param x 加数
     * @param y 被加数
     * @return 结果
     */
    @Override
    public String add(int x, int y) {
        System.out.println("x + y = ?");
        return x + y + "";
    }
}



package webservice;

import javax.jws.WebService;

/**
 * Created by Juxuny on 2014/9/24.
 */
@WebService
public interface HelloWorld {
    public String add(int x ,int y);
}

运行后,在浏览器打开下面的URL,能够看到一个 xml文件就表示成功了



二、客户端

使用wsimport 指令创建客户端

wsimport -p hello -keep http://localhost:8888/hello?wsdl

运行完之后会见到一个目录hello

还可以创建成jar包 

wsimport -p hello -keep http://localhost:8888/hello?wsdl -clientjar hello.jar






将这个jar添加到自己的工程之后,就可以调用WebService

package test;

import hello.HelloWorld;
import hello.MyHelloService;
import hello.ObjectFactory;

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

/**
 * Created by Juxuny on 2014/9/24.
 */
public class Main {

    public static void main(String[] args) throws MalformedURLException {
        MyHelloService myHelloService = new MyHelloService(new URL("http://localhost:8888/hello"));
        HelloWorld helloWorld = myHelloService.getMyHelloPort();
        System.out.println(helloWorld.add(1,3));
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值