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

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拦截跨域请求的问题


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值