同源策略是指:协议、主机和端口都相同。我们可以在本地机器上部署2个不同端口的tomcat,让一个tomcat下的应用通过ajax访问另一个tomcat下的rest服务,这样就存在跨域访问问题了。修改conf/server.xml下面的三处端口号:
<Server port="****" shutdown="SHUTDOWN"> <Connector port="****" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> <Connector port="****" protocol="AJP/1.3" redirectPort="8443" />
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-extension-providers</artifactId> <version>${cxf.version}</version> </dependency>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <jaxrs:server address="/rest"> <jaxrs:serviceBeans> <ref bean="nameServiceImpl"/> </jaxrs:serviceBeans> <!--jsonp--> <jaxrs:providers> <bean class="org.apache.cxf.jaxrs.provider.jsonp.JsonpPreStreamInterceptor"/> </jaxrs:providers> <jaxrs:inInterceptors> <bean class="org.apache.cxf.jaxrs.provider.jsonp.JsonpInInterceptor"/> </jaxrs:inInterceptors> <jaxrs:outInterceptors> <bean class="org.apache.cxf.jaxrs.provider.jsonp.JsonpPostStreamInterceptor"/> </jaxrs:outInterceptors> </jaxrs:server> </beans>
3.在另一个tomcat下通过ajax访问
$.ajax({ type: 'get',url: 'http://127.0.0.1:8080/aty-rest/rest/rest/welcome',dataType: 'jsonp',jsonp: '_jsonp',jsonpCallback: 'callback',success: function(data) { alert(JSON.stringify(data)); } });
本文参考了 Web Service 那点事儿(4)—— 使用 CXF 开发REST服务 这篇很不错的入门文章。
原文链接:/ajax/163543.html