本文共 1721 字,大约阅读时间需要 5 分钟。
在控制器(@Controller)类或特定方法上使用@CrossOrigin注解,可以实现局部跨域的支持。
@RestController@CrossOrigin(allowCredentials="true")public class CorsTestController { @RequestMapping("/test") public String preUser(){ System.out.println("test"); return "test";}} 这里的allowCredentials="true"属性用于允许跨域请求携带cookie信息,当需要维护会话时需要开启该属性。其他属性可参考注解文档进行调整。
通过配置全局的跨域设置,可以实现对整个应用的跨域支持。
@Configurationpublic class CORSWebMvcConfiguration extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("*") .allowedOrigins("*") .exposedHeaders("token") .allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE");}} 这种方式适合需要对整个应用进行统一跨域配置的情况,设置简单且灵活。
通过自定义过滤器实现跨域支持,可以具备更高的灵活性和定制性。
package com.example.pahms.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;@Configurationpublic class GlobalCorsConfig { @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.setAllowCredentials(true); config.addAllowedMethod("*"); config.addAllowedHeader("*"); config.addExposedHeader("token"); UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**", config); return new CorsFilter(configSource); }} 这种方式适合需要对特定路径或资源进行跨域配置时,能够提供更细粒度的控制。
转载地址:http://ctmg.baihongyu.com/