您的位置:首页 > 其它

Tuscany发布Web Service示例

2012-12-10 20:09 197 查看
这里举个Hello world的例子演示使用Tuscany发布Web Service。首先maven创建web项目,结构如下



maven引用如下



web.xml如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

<display-name>myws</display-name>

<filter>
<filter-name>tuscany.myws</filter-name>
<filter-class>org.apache.tuscany.sca.host.webapp.TuscanyServletFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>tuscany.myws</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list id="WelcomeFileList">
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>
HelloService接口如下

package myws;

import org.oasisopen.sca.annotation.Remotable;

@Remotable
public interface HelloService {

String sayHello(String name);

}


实现类如下

package myws;

public class HelloServiceImpl implements HelloService{

@Override
public String sayHello(String name) {
return "Hello " + name;
}

}
web.composite配置文件如下

<?xml version="1.0" encoding="UTF-8"?>
<composite xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912"
xmlns:tuscany="http://tuscany.apache.org/xmlns/sca/1.1"
targetNamespace="http://myws"
name="myws">

<component name="HelloComponent">
<implementation.java class="myws.HelloServiceImpl"/>
<service name="HelloService">
<binding.ws uri="http://localhost:8080/HelloComponent/HelloService"/>
</service>
</component>

</composite>
将项目部署于tomcat运行,用浏览器测试如下



java客户端测试如下。测试时可能会抛出异常:java.lang.ClassNotFoundException: org.apache.http.HttpResponseFactory,是因为少JAR包。如果用过Axis2,可以去它里面找httpcore-4.0.jar,引入项目即可。

package test;

import javax.xml.namespace.QName;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

public class HelloClient {

public static void main(String[] args) throws AxisFault {
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
//设定服务提供者的地址
EndpointReference targetEPR = new EndpointReference("http://localhost:8080/myws/HelloComponent/HelloService");
options.setTo(targetEPR);
//设定所要调用的服务的操作
QName qName = new QName("http:///myws", "sayHello");
Class[] returnTypes = new Class[] { String.class };
//设定调用的方法的参数值
Object[] params = new Object[] { "World" };
//得到调用的结果
Object[] response = serviceClient.invokeBlocking(qName,params,returnTypes);
String result = (String) response[0];;
//如果调用失败
if (result == null) {
System.out.println("服务调用失败!");
return;
}
//显示调用的结果
System.out.println(result);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: