EJB2.1可以将无状态会话Bean暴露为WebService
1.定义WebService服务接口(Endpoint Inteface),通过标注@WebService来指明这是一个WebService的服务接口,通过标注@WebMethod来指明要暴露的服务方法,@WebMethod是可选的,如果没有指明@WebMethod,则所有方法暴露为WebService服务方法。
package examples.ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface HelloWorld {
@WebMethod
public String hello();
}
2.实现一个无状态的会话Bean,实现服务接口。通过标注@WebService指明该无状态的会话Bean暴露为WebService,@WebService的属性endpointInterface指明WebService服务接口。
package examples.ws;
import javax.ejb.Stateless;
import javax.jws.WebService;
@WebService(endpointInterface="examples.ws.HelloWorld",serviceName="Greeter",portName="GreeterPort")
@Stateless
public class HelloBean implements HelloWorld {
public String hello() {
return "Hello World";
}
}
3.将上述EJB发布到EJB容器中。EJB容器会生成相应得WSDL文件和WebService.xml,也可以自己提供WSDL文件和WebService.xml,放在EJB-jar的META-INF文件夹下。生成得wsdl文件片段如下:
<service name="Greeter">
<port name="GreeterPort" binding="tns:GreeterPortBinding">
<soap:address location="http://[host]:8080/Greeter/HelloBean" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"/>
</port>
</service>
4.客户端代码:
import examples.ws.HelloWorld;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class WebServiceClient {
static String host = "localhost";
static String portType = "HelloBean";
static String serviceName = "Greeter";
static String serviceEndpointAddress = "http://" + host + ":8080/" + serviceName;
static String nameSpace = "http://ws.examples/";
public static void main(String[] args) throws Exception
{
URL wsdlLocation = new URL(serviceEndpointAddress + "/" + portType + "?WSDL");
QName serviceNameQ = new QName(nameSpace, serviceName);
Service service = Service.create(wsdlLocation, serviceNameQ);
HelloWorld client = (HelloWorld)service.getPort(HelloWorld.class);
System.out.println(client.hello());
}