一开始使用spring自带的cores过滤器来处理,结果发现,如果请求不进入spring的话,跨域问题根本解决不了,例如:自定义一个登陆拦截器用来处理登录状态,如果状态不对直接抛异常,那么,这个抛异常就不会在进入spring,spring里自带的cors自然不会起作用
解决方式:
1,自定义一个过滤器,自定义的过滤器会在自定义的拦截器之前就执行,不再使用spring自带的过滤器,百度复制黏贴即可
2,通过配置父容器中的一个filter,不再把cors放在springmvc中
我们的自定义拦截器之所以会优先执行,是因为其配置在了web.xml里边,tomcat一启动就加载执行
1,把corsFilter配置在父容器中
<bean id="corsFilter" class="org.springframework.web.filter.CorsFilter">
<constructor-arg name="configSource">
<bean class="org.springframework.web.cors.UrlBasedCorsConfigurationSource">
<property name="corsConfigurations">
<map >
<entry key="/**">
<bean class="org.springframework.web.cors.CorsConfiguration">
<property name="allowedMethods" value="*"/>
<property name="allowedHeaders" value="*"/>
<property name="allowCredentials" value="false"/>
<property name="allowedOrigins" value="*"/>
</bean>
</entry>
</map>
</property>
</bean>
</constructor-arg>
</bean>
2.让web.xml来加载
<filter>
<filter-name>delegatingFilterProxy</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>corsFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>delegatingFilterProxy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>