SpringBoot 面试题, Spring Boot 如何处理跨域请求CORS?
SpringBoot 面试题, Spring Boot 如何处理跨域请求CORS?
QA
Step 1
Q:: Spring Boot 如何处理跨域请求(CORS)?
A:: 在 Spring Boot 中,可以通过多种方式处理跨域请求(CORS)。最简单的方法是使用 @
CrossOrigin 注解,直接在控制器或方法上进行配置。例如:
@RestController
@CrossOrigin(origins = "http://example.com")
public class ExampleController {
@GetMapping("/example")
public ResponseEntity<String> getExample() {
return ResponseEntity.ok("Hello, CORS");
}
}
另外,还可以通过配置类进行全局配置:
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 implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(true)
.maxAge(3600);
}
}
Step 2
Q:: 什么是 Spring Boot?
A:: Spring Boot 是 Spring 框架的一个模块,用于简化新 Spring 应用的初始搭建及开发过程。通过提供默认配置和自动化配置机制,Spring Boot 极大地减少了开发人员的工作量。其主要特点包括创建独立运行的 Spring 应用、内嵌 Web 服务器、简化的 Maven 配置、自动配置 Spring 和第三方库、以及无代码生成和无需 XML 配置。
Step 3
Q:: Spring Boot 有哪些核心注解?
A:: Spring Boot 提供了一些核心注解,包括:
1. @SpringBootApplication:这是一个组合注解,包含 @Configuration、@EnableAutoConfiguration 和 @
ComponentScan,用于标记主应用类。
2. @RestController:结合了 @Controller 和 @
ResponseBody,用于创建 RESTful Web 服务。
3. @
RequestMapping:用于映射 HTTP 请求到控制器的方法。
4. @
Autowired:用于自动装配依赖。
5. @Component、@Service、@
Repository:用于标记 Spring 组件、服务类和持久层类。
用途
CORS(跨域资源共享)是一个浏览器机制,允许来自不同域的服务器进行通信。处理跨域请求在现代 Web 应用中尤为重要,因为前端应用和后端 API 往往部署在不同的域中。了解如何在 Spring Boot 中配置和处理 CORS 是确保应用安全性和功能性的重要部分。\n相关问题
🦆
什么是 CORS?▷
🦆
如何在 Spring Boot 中处理静态资源?▷
🦆
Spring Boot 如何处理错误和异常?▷
🦆
Spring Boot 如何集成 MyBatis?▷