您好,登錄后才能下訂單哦!
在Spring Boot應(yīng)用程序中配置跨域資源共享(CORS)策略可以通過(guò)多種方式實(shí)現(xiàn),以下是幾種常見的方法:
@CrossOrigin
注解你可以在控制器類或方法上使用@CrossOrigin
注解來(lái)配置CORS策略。例如:
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "http://localhost:8080")
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
在這個(gè)例子中,@CrossOrigin
注解指定了允許的源(origins),這里是http://localhost:8080
。
你也可以在Spring Boot應(yīng)用程序中配置全局的CORS策略。這可以通過(guò)實(shí)現(xiàn)WebMvcConfigurer
接口來(lái)完成。例如:
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 MyAppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}
在這個(gè)例子中,addCorsMappings
方法定義了全局的CORS策略。/**
表示允許所有路徑,allowedOrigins
指定了允許的源,allowedMethods
指定了允許的HTTP方法,allowedHeaders
指定了允許的請(qǐng)求頭,allowCredentials
表示是否允許發(fā)送Cookie。
你還可以通過(guò)自定義一個(gè)Filter來(lái)實(shí)現(xiàn)CORS策略。例如:
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
// 其他必要的方法,如init()和destroy()
}
然后,你需要在Spring Boot配置類中注冊(cè)這個(gè)Filter:
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyAppConfig {
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new CorsFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}
在這個(gè)例子中,FilterRegistrationBean
用于注冊(cè)自定義的CorsFilter
,并指定它應(yīng)該應(yīng)用于所有URL模式。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。