在SpringBoot中處理跨域資源共享可以通過以下幾種方式:
@CrossOrigin(origins = "http://example.com")
@RestController
public class MyController {
// controller methods
}
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://example.com");
}
};
}
}
@Component
public class CustomCorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "http://example.com");
filterChain.doFilter(request, response);
}
}
這些方法可以根據具體的需求選擇其中一種或者多種來處理跨域資源共享。