首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 互联网 >

JAX-WS 学习1:创建服务接口

2012-07-26 
JAX-WS 学习一:创建服务接口Java1.6中自带了JAX-WS API,使得我们可以很方便、简单的开发一个基于Java的WebS

JAX-WS 学习一:创建服务接口

Java1.6中自带了JAX-WS API,使得我们可以很方便、简单的开发一个基于Java的WebService应用。下面看一个JAX-WS中的HelloWord应用。

?

一、创建WebService Endpoint接口

首先我们来定义Server端的WebService服务接口,如下:

package test;import javax.jws.WebService;@WebServicepublic interface Calculator {public int add(int a, int b);public int multi(int a, int b);}

?

这里看到在类定义上,加了一个“@WebService”的annotation,这是定义JAX-WS定义WebService的关键,这个annotation用来告诉java解析器你希望把这个接口中的方法发布成一些WebService的服务。

?

有了接口定义,下面给出一个实现:

package test;import javax.jws.WebService;@WebService(endpointInterface = "test.Calculator")public class CalculatorImpl implements Calculator {public int add(int a, int b) {return a + b;}public int multi(int a, int b) {return a * b;}public int minus(int a, int b) {return a - b;}}

?

?这里WebService annotation里加了一个参数"endpointInterface",这个参数用来指定这个WebService的抽象服务接口,例如此处如果不用"endpointInterface"指定接口,那么生成的WebService服务有三个操作"add","multi"和"minus",也就是定义在当前类中的方法集;如果指定了endpointInterface,则只有"add","multi",即定义在Calculator中的方法集。

?

二、发布服务

?

上面就已经定义好了服务接口和服务实现类,然后就可以发布了。发布也是相当的简单,只需要一条语句:

package test;import javax.xml.ws.Endpoint;public class Server {public static void main(String[] args) {Endpoint.publish("http://localhost:8088/calculator",new CalculatorImpl());}}

?这里publish方法需要两个参数:

address:服务对外暴露的用于调用服务的地址implementor:服务的实现对象

启动这个Server类,就可以访问服务了。要测试服务有没有启动,可以输入ttp://localhost:8088/calculator?wsdl,如果一切正常,就可以看到一个wsdl定义内容,表示服务已经成功启动。

?

三、annotations

使用jax-ws时,有两个重要的annotation:

@WebService

此注示用来标明此java类为某个WebService的实现类或者标明此java接口定义了某个WebService的接口。@WebService有六个参数可以用来配置这个WebService的定义:?

    ?
      endpointInterface:上面已经介绍了,指向一个定义此WebService抽象定义接口的完整类路径name:WebService名;默认的port名为"实现类名+Port",binding名为"实现类名+PortBinding",通过指定name的值来替换 实现类名。portName:指定port名,可以完成替换默认port名,或由上面的"name"指定的port名。targetNamespace:指定targetNamespace值,默认的值为 "http://包名/",可以通过此变量指定一个自定义的targetNamespace值。(注:如果分别定义和接口和实现,则他们有各自的targetNamespace)serviceName:指定service名wsdlLocation:指向一个预定义的wsdl的文件,替代自动生成的wsdl文件。
@WebMethod
    action:指定此方法对应的actionexclude:true --表示此方法包含在web服务中;false表示排除此方法operationName:指定方法对应的operation的名字。

?

热点排行