webservice例子及跨域访问配置

<script type="text/javascript"><!-- document.domain = "iteye.com"; // --></script>

1 实现jax-ws规范的webservice

2 配置跨域访问

 

(1)下载jax-ws lib包

(2)创建webservice接口

 

package com.iit.server;

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

@WebService
public interface IHelloService {
	
	
	@WebMethod String helloWorld();
}

 (3)实现接口

package com.iit.server;

import javax.jws.WebService;

@WebService(endpointInterface = "com.iit.server.IHelloService")
public class HelloServiceImpl implements IHelloService{

	
	public String helloWorld() {
		// TODO Auto-generated method stub
		return "Hi I am Return";
	}

}

 (4)发布webservice,jax2.0有2种发布方式,一种是通过一个main函数来实现类型web服务器发布的模式,另外一种是在web服务器种发布,下面是main函数实现的发布

 

package com.iit.server;

import javax.xml.ws.Endpoint;
import javax.xml.ws.http.HTTPBinding;

public class SoapServer {

	public static void main(String args[]){
		 
		 HelloServiceImpl service= new HelloServiceImpl();  

		 Endpoint.publish("http://123.14.137.164:8080/hello", service);  
	}
}

 (5)访问

http://123.14.137.164:8080/hello?wsdl来观察结果
2 配置跨域访问

创建
package com.iit.server;

import java.io.StringReader;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.Provider;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceProvider;

@WebServiceProvider
public class CrossDomainProvider implements Provider<Source> {
	public Source invoke(Source request) {
		System.out.print(request);

		String replyData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
				+ "<access-policy>" + "<cross-domain-access>" + "<policy>"
				+ "<allow-from http-request-headers=\"*\">"
				+ "<domain uri=\"*\"/>" + "</allow-from>" + "<grant-to>"
				+ "<resource path=\"/\" include-subpaths=\"true\"/>"
				+ "</grant-to>" + "</policy>" + "</cross-domain-access>"
				+ "</access-policy>";
		StreamSource reply = new StreamSource(new StringReader(replyData));
		return reply;
	}

}
 

在发布时加入:package com.iit.server;

import javax.xml.ws.Endpoint;
import javax.xml.ws.http.HTTPBinding;

public class SoapServer {

	public static void main(String args[]){
		 Endpoint e = Endpoint.create(HTTPBinding.HTTP_BINDING, new CrossDomainProvider());  

		 e.publish("http://123.14.137.164:8080/clientaccesspolicy.xml");  

		 HelloServiceImpl service= new HelloServiceImpl();  

		 Endpoint.publish("http://123.14.137.164:8080/hello", service);  
	}
}
 

注意:(在文本服务器发布的时候 可以手动生产一个clientaccesspolicy.xml文件,这个文件需要放在web服务器根目录中。)

你可能感兴趣的:(webservice)