gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Springboot中如何配置跨域?
- User
Springboot中如何配置跨域?
- Assistant
Springboot中如何配置跨域?
在Spring Boot中配置跨域(CORS,Cross-Origin Resource Sharing)可以通过多种方式实现。以下是几种常见的方法:
@CrossOrigin注解如果你只需要为特定的控制器或方法配置跨域,你可以使用@CrossOrigin注解。
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@CrossOrigin(origins = "http://example.com")
@GetMapping("/api/data")
public String getData() {
return "Hello World";
}
}
如果你需要全局配置跨域,可以使用WebMvcConfigurer配置类。
import org.springframework.context.annotation.Bean;
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 WebConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许所有路径
.allowedOrigins("http://example.com") // 允许的域
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法
.allowedHeaders("*") // 允许的头部信息
.allowCredentials(true) // 是否允许发送Cookie信息
.maxAge(3600); // 缓存时间
}
};
}
}
还可以通过创建一个过滤器来配置跨域。
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Content-Length, X-Requested-With");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Max-Age", "3600");
HttpServletRequest req = (HttpServletRequest) request;
if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
res.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
通过上述方法,你可以根据需要在Spring Boot应用中灵活配置跨域。
Not yet included in a published release.