在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);
}
}
这些方法可以根据具体的需求选择其中一种或者多种来处理跨域资源共享。