温馨提示×

springboot怎么解决跨域问题

小亿
95
2023-10-25 18:37:31
栏目: 编程语言

在Spring Boot中解决跨域问题可以通过以下几种方式:

  1. 使用注解@EnableWebMvc和@CrossOrigin:在Spring Boot的启动类上添加@EnableWebMvc注解,并在Controller的方法上添加@CrossOrigin注解即可实现跨域访问。例如:
@SpringBootApplication
@EnableWebMvc
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
@RestController
public class MyController {
    @CrossOrigin(origins = "http://localhost:8081")
    @GetMapping("/hello")
    public String hello() {
        return "Hello World!";
    }
}
  1. 使用WebMvcConfigurer配置跨域:创建一个配置类实现WebMvcConfigurer接口,在其中重写addCorsMappings方法,设置允许跨域的路径和允许跨域的请求方式。例如:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8081")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowCredentials(true)
                .maxAge(3600);
    }
}
  1. 使用Filter过滤器配置跨域:创建一个CorsFilter类继承自javax.servlet.Filter,通过重写doFilter方法来实现跨域处理。例如:
@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", "http://localhost:8081");
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("Access-Control-Allow-Max-Age", "3600");
        chain.doFilter(request, response);
    }
}

以上是一些常用的解决跨域问题的方式,根据实际需求选择其中一种即可解决问题。

0