您的位置:首页 > 编程语言 > Java开发

spring mvc4.2与spring-session整合后的跨域配置

2017-06-16 23:46 260 查看
spring mvc4.2之后增加了CORS跨域配置支持,这功能不错,我非常喜欢,可以通过java的Annotation方式配置,也可以在spring的xml文件中配置。比如这样:

<mvc:cors>
<mvc:mapping path="/**"
allowed-origins="http://localhost:8090"
allowed-methods="GET, POST, OPTIONS, PUT, DELETE"
allowed-headers="Accept, Origin, X-Requested-With, Content-Type, Last-Modified, Set-Cookie, x-auth-token"
exposed-headers="Accept, Origin, X-Requested-With, Content-Type, Last-Modified, Set-Cookie, x-auth-token"
allow-credentials="true"
max-age="3600" />
</mvc:cors>


非常方便,也可以在Controller类上加入这个注解

@CrossOrigin(origins = "http://www.baidu.com", maxAge = 3600)
想要了解更多的可以参考:http://blog.csdn.net/z69183787/article/details/53102112

跨域配置后,与spring-session整合会出现跨域请求还没到springmvc的CorsFilter,就被spring-session拦截掉并拿不到cookie,导致拿不到session标识。

这该如何解决呢,经过分析springmvcCorsFilter的源码,找到一个解决方法,就是将CorsFilter放在spring-session之前,使跨域请求先经过CorsFilter,再经过spring-session,就可以解决了。

在web.xml中插入CorsFilter为第一个Filter

<filter>
<filter-name>corsFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在spring-config.xml中去掉<mvc:cors/>配置,改为以下配置示例

<bean id="corsFilter" class="org.springframework.web.filter.CorsFilter">
<constructor-arg index="0">
<bean class="org.springframework.web.cors.UrlBasedCorsConfigurationSource">
<property name="corsConfigurations">
<map>
<entry key="/**">
<bean class="org.springframework.web.cors.CorsConfiguration">
<property name="allowedOrigins">
<list>
<value>http://127.0.0.1:8090</value>
<value>http://localhost:8090</value>
</list>
</property>
<property name="allowedMethods" value="*"></property>
<property name="allowedHeaders" value="*"></property>
<property name="exposedHeaders">
<list>
<value>Accept</value>
<value>Origin</value>
<value>X-Requested-With</value>
<value>Content-Type</value>
<value>Last-Modified</value>
<value>Set-Cookie</value>
<value>x-auth-token</value>
</list>
</property>
<property name="allowCredentials" value="true"></property>
<property name="maxAge" value="3600"></property>
</bean>
</entry>
</map>
</property>
</bean>
</constructor-arg>
</bean>


这样就解决了先被spring-session拦截跨域请求的问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐