spring如何请求跨域资源
-
要实现Spring跨域请求,你可以通过以下几种方法:
- 使用CORS(跨源资源共享)过滤器
CORS是一种在跨域请求中使用的标准机制,可以通过配置过滤器来实现跨域请求。在Spring中,可以通过配置一个CORS过滤器来允许跨域请求。具体步骤如下:
- 创建一个类实现
javax.servlet.Filter接口,实现doFilter()方法。 - 在
doFilter()方法中设置响应头中的CORS相关参数,允许跨域请求的域名、方法、头部等信息。 - 在Spring配置文件中配置该过滤器。
- 使用Spring MVC的注解方式实现跨域请求
Spring MVC提供了@CrossOrigin注解,可以在控制器方法上标注该注解,从而允许该方法接受跨域请求。具体步骤如下:
- 在控制器的方法上标注
@CrossOrigin注解,并设置允许跨域请求的来源、方法、头部等信息。
- 使用Spring Security进行跨域请求配置
如果你的项目中使用了Spring Security,可以通过配置Spring Security来实现跨域请求。具体步骤如下:
- 在Spring Security配置类中,重写
configure(HttpSecurity http)方法。 - 在该方法中,配置
http.cors()来允许跨域请求。
以上是几种常用的Spring实现跨域请求的方法。根据你的具体需求和项目配置,选择其中一种来实现跨域请求即可。
1年前 - 使用CORS(跨源资源共享)过滤器
-
在Spring中,实现跨域资源共享(Cross-Origin Resource Sharing,CORS)可以通过以下几种方式:
- 使用注解 @CrossOrigin
Spring提供了一个 @CrossOrigin 注解,可以直接在Controller的方法上添加,用于配置跨域请求的细节。通过设置该注解的属性,可以指定允许跨域的域名、请求方法、请求头等。例如:
@RestController public class MyController { @CrossOrigin(origins = "http://example.com") @GetMapping("/getData") public String getData() { // 处理请求 } }- 使用WebMvcConfigurer接口
通过实现WebMvcConfigurer接口,并在其addCorsMappings方法中配置跨域请求的细节。示例代码如下:
@Configuration public class MyConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/getData") .allowedOrigins("http://example.com") .allowedMethods("GET") .allowedHeaders("header1", "header2") .allowCredentials(true); } }- 使用Filter
通过实现javax.servlet.Filter接口,可以在请求到达Controller之前,对请求进行处理,并设置跨域相关的响应头。示例代码如下:
@Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; response.setHeader("Access-Control-Allow-Origin", "http://example.com"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "header1, header2"); response.setHeader("Access-Control-Allow-Credentials", "true"); filterChain.doFilter(servletRequest, servletResponse); } // 其他方法... }- 使用spring-boot-starter-data-redis库
通过使用spring-boot-starter-data-redis库,可以在Spring中使用Redis来实现CORS。示例代码如下:
@Configuration public class CorsConfiguration { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("http://example.com"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }- 使用WebSecurityConfigurerAdapter
如果Spring应用中使用了Spring Security,可以通过继承WebSecurityConfigurerAdapter类,重写configure方法来配置跨域请求。示例代码如下:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(); } }以上是在Spring中实现跨域资源共享的几种方式。根据具体的需求,可以选择适合自己项目的方式来处理跨域请求。
1年前 - 使用注解 @CrossOrigin
-
一、什么是跨域资源共享(CORS)
跨域资源共享(Cross-origin resource sharing,简称CORS)是一种机制,它允许服务器在响应中添加一个许可证头,以允许在不同源(域、协议、端口)之间的Web应用程序访问其资源。
在默认情况下,浏览器的同源策略限制了来自不同源的网页对资源的访问,跨域请求(如Ajax请求)将被浏览器拒绝。通过添加CORS头,服务器可以选择允许特定源或所有源请求其资源。
二、Spring中配置CORS支持
在Spring中,可以通过以下几种方式来配置CORS支持:
- 使用
@CrossOrigin注解 - 使用
WebMvcConfigurer接口 - 使用
Filter
下面将详细介绍这三种配置CORS支持的方式。
- 使用
@CrossOrigin注解
在控制器类或控制器方法上使用
@CrossOrigin注解可以启用CORS支持。示例:
@RestController @CrossOrigin(origins = "http://localhost:8080") public class MyController { @GetMapping("/hello") public String hello() { return "Hello!"; } }上述代码中,
@CrossOrigin注解指定了允许来源为"http://localhost:8080"的跨域请求。如果不指定`origins`参数,默认允许所有来源的请求。- 使用
WebMvcConfigurer接口
创建一个实现了
WebMvcConfigurer接口的配置类,并重写addCorsMappings方法来配置CORS支持。示例:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:8080") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowCredentials(true) .maxAge(3600); } }上述代码中,
addCorsMappings方法配置了允许所有路径下的跨域请求,并指定了允许的方法、是否允许携带认证信息、缓存时间等。- 使用
Filter
使用
Filter可以在请求到达控制器之前进行预处理,通过添加自定义的CORSFilter来实现CORS支持。示例:
@Component public class CORSFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:8080"); httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpResponse.setHeader("Access-Control-Max-Age", "3600"); chain.doFilter(request, response); } }上述代码中,
doFilter方法添加了CORS头,允许指定的跨域请求。三、CORS配置细节
除了上述介绍的基本配置之外,还可以根据实际需求进行更细粒度的配置。
allowedHeaders:允许的请求头,默认为允许所有请求头。exposedHeaders:允许暴露给前端的响应头。allowCredentials:是否允许发送Cookie,默认为不允许。maxAge:预检请求的缓存时间,单位为秒。allowedMethods:允许的请求方法。
示例:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:8080") .allowedMethods("GET", "POST") .allowedHeaders("Authorization") .exposedHeaders("Access-Control-Allow-Headers") .allowCredentials(true) .maxAge(3600); } }上述代码中,只有路径为
/api/**的请求才会被允许跨域,并且只允许使用GET和POST方法,同时指定了允许的请求头和响应头,以及是否允许发送Cookie和预检请求的缓存时间。四、总结
以上就是Spring中配置CORS支持的几种方式。根据实际需求,可以选择使用
@CrossOrigin注解、WebMvcConfigurer接口或Filter来实现CORS支持。配置CORS可以使得服务器能够处理跨域请求,从而实现安全可靠的资源共享。1年前 - 使用