同源策略是指:协议、主机和端口都相同。我们可以在本地机器上部署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" />
在上一篇博客的基础上,为了解决cxf跨域问题需要:
1.修改pom文件,增加providers
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-extension-providers</artifactId> <version>${cxf.version}</version> </dependency>
2.修改cxf-spring.xml配置jsonp拦截器
<?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)); } });
JAX-RS开发(三):ajax访问REST服务时的跨域问题
原文地址:http://blog.csdn.net/aitangyong/article/details/45030231