spring boot如何实现跨域
-
Spring Boot实现跨域有两种方式:一种是通过添加注解实现,另一种是通过配置类实现。
- 添加注解实现跨域:
在Controller类或者方法上添加@CrossOrigin注解,可以指定允许访问的域名、请求头、请求方法等信息。
示例代码如下:
@RestController public class UserController { @CrossOrigin(origins = "http://example.com") @GetMapping("/user") public User getUser() { // TODO: 返回用户信息 } }上述代码表示允许来自
http://example.com域名的访问。- 使用配置类实现跨域:
创建一个配置类,并实现WebMvcConfigurer接口,重写addCorsMappings方法,配置允许跨域的规则。
示例代码如下:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://example.com") .allowedMethods("GET", "POST") .allowedHeaders("header1", "header2") .allowCredentials(true) .maxAge(3600); } }上述代码表示只允许
http://example.com域名下的请求访问,允许的请求方法为GET和POST,允许的请求头为header1和header2,允许携带cookie,最大缓存时间为3600秒。通过使用以上两种方式的其中一种,可以在Spring Boot中实现跨域访问。
1年前 -
Spring Boot可以通过使用CorsFilter过滤器、自定义@CrossOrigin注解、使用WebMvcConfigurer等方式来实现跨域。
-
使用CorsFilter过滤器:在Spring Boot中,可以通过自定义一个CorsFilter过滤器来处理跨域请求。
首先,创建一个继承自OncePerRequestFilter的CorsFilter类,并在doFilterInternal方法中添加相关的跨域配置。
示例代码如下:import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CorsFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type"); response.setHeader("Access-Control-Max-Age", "3600"); chain.doFilter(request, response); } }接下来,在Spring Boot的配置类中注册该过滤器:
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CorsConfig { @Bean public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean() { FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>(); CorsFilter corsFilter = new CorsFilter(); registrationBean.setFilter(corsFilter); registrationBean.setOrder(0); return registrationBean; } }通过上述配置,所有的请求都可以跨域访问。
-
使用@CrossOrigin注解:在Controller类的方法上加上@CrossOrigin注解也可以实现跨域请求。
示例代码如下:import org.springframework.web.bind.annotation.*; @RestController @CrossOrigin(origins = "*") public class ExampleController { @GetMapping("/example") public String exampleMethod() { return "Hello world"; } }通过上述配置,该方法允许来自任意域名的跨域访问。
-
使用WebMvcConfigurer:通过自定义WebMvcConfigurer配置类,可以全局配置跨域请求。
示例代码如下:import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("Authorization", "Content-Type") .maxAge(3600); } }通过上述配置,所有的请求都可以跨域访问。
-
配置跨域请求允许的域名:可以通过配置文件(application.properties或application.yml)来指定允许进行跨域请求的域名。
示例代码如下:# application.properties spring.mvc.allow-request-from = example.com或者:
# application.yml spring: mvc: allow-request-from: example.com通过上述配置,只允许来自example.com域名的请求进行跨域访问。
-
其他配置:除了上述方法,还可以根据具体需求进行其他自定义配置,例如:
- 在Spring Security中配置跨域请求;
- 在Spring WebSocket中配置跨域请求;
- 使用第三方库进行跨域请求配置等。
总结起来,Spring Boot提供了多种灵活的方式来实现跨域请求的处理,根据具体需求选择合适的方式进行配置即可。
1年前 -
-
跨域是由浏览器的同源策略(Same Origin Policy)所限制的,即浏览器只允许发送同源(协议、域名、端口号都相同)的请求。而当网页中的代码需要访问不同的域的资源时,就属于跨域请求。对于后端开发来说,Spring Boot提供了多种方式来解决跨域请求的问题,下面将介绍这些方式。
- 使用WebMvcConfigurer配置跨域请求
可以通过实现WebMvcConfigurer接口来自定义WebMvc配置,并重写addCorsMappings方法来配置跨域请求。
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("*") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }在上述代码中,通过addCorsMappings方法配置了允许所有的请求路径("/**")进行跨域访问,allowedOrigins配置允许的来源,allowedMethods配置允许的HTTP方法,allowedHeaders配置允许的头信息,allowCredentials配置是否允许发送Cookie,maxAge配置缓存时间。
- 使用@CrossOrigin注解配置跨域请求
使用@CrossOrigin注解可以在方法上直接配置允许跨域请求的参数,例如:
@RestController @RequestMapping("/api") @CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}) public class ApiController { // ... }在上述代码中,@CrossOrigin注解配置了允许所有的请求路径("/api")进行跨域访问,origins配置允许的来源,allowedHeaders配置允许的头信息,methods配置允许的HTTP方法。
- 使用Filter过滤器实现跨域请求
通过编写一个Filter来处理跨域请求,实现javax.servlet.Filter接口,并重写doFilter方法。
@Component @WebFilter(filterName = "CorsFilter") public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpRequest.addHeader("Access-Control-Allow-Origin", "*"); httpRequest.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); httpRequest.addHeader("Access-Control-Allow-Headers", "Content-Type"); httpRequest.addHeader("Access-Control-Max-Age", "3600"); chain.doFilter(request, response); } // ... }在上述代码中,通过doFilter方法设置响应头信息,允许所有的来源("*"),允许的HTTP方法(GET、POST、PUT、DELETE),允许的头信息(Content-Type),缓存时间(3600秒)。
- 使用CorsFilter过滤器实现跨域请求
Spring Boot提供了一个CorsFilter过滤器,可以直接使用它来处理跨域请求。只需将以下配置加到application.properties或application.yml文件中即可。
spring.webmvc.cors.allowed-origins=* spring.webmvc.cors.allowed-methods=GET, POST, PUT, DELETE spring.webmvc.cors.allowed-headers=Content-Type spring.webmvc.cors.allow-credentials=true spring.webmvc.cors.max-age=3600在上述配置中,allowed-origins配置允许的来源,allowed-methods配置允许的HTTP方法,allowed-headers配置允许的头信息,allow-credentials配置是否允许发送Cookie,max-age配置缓存时间。
除了以上介绍的几种方式外,还可以使用Spring Security来配置跨域请求,根据实际需求选择合适的方式来解决跨域问题。
1年前