Java后端配置允许跨域方式

 更新时间:2025年02月06日 09:33:28   作者:白天睡晚上卷  
本文介绍了在不同技术和框架中配置跨域资源共享(CORS)的方法,包括使用SpringMVC的@CrossOrigin注解、SpringBoot的全局CORS配置、SpringSecurity中的CORS集成以及手动设置响应头,根据具体需求和技术栈,选择合适的方法来确保跨域请求的安全性和有效性

1. 使用 @CrossOrigin 注解 (Spring MVC)

如果你使用的是Spring MVC或Spring Boot,最简单的方法是直接在控制器类或方法上使用@CrossOrigin注解来允许特定来源的跨域请求。

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "http://example.com") // 允许来自example.com的跨域请求
public class MyController {

    @GetMapping("/api/data")
    public String getData() {
        return "Data from server";
    }
}

你可以指定多个来源,或者使用*来允许所有来源(但不推荐用于生产环境):

@CrossOrigin(origins = "*") // 允许所有来源

2. 配置全局 CORS 支持 (Spring Boot)

为了在整个应用程序中统一配置CORS规则,而不是逐个控制器或方法进行配置,可以通过实现WebMvcConfigurer接口并在其中定义全局的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 {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**") // 应用于所有路径
                    .allowedOrigins("http://example.com") // 允许的来源
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法
                    .allowCredentials(true) // 是否允许发送凭证信息(如Cookies)
                    .maxAge(3600); // 预检请求的有效期(秒)
            }
        };
    }
}

3. 使用 Spring Security 配置 CORS (如果使用了 Spring Security)

如果你的应用程序使用了Spring Security,你还需要确保在安全配置中也启用了CORS支持。

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            .csrf().disable(); // 根据需要启用或禁用CSRF保护
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://example.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

4. 手动设置响应头 (Servlet API)

对于不使用Spring框架的项目,可以在Servlet中手动设置响应头来允许跨域请求。

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 设置CORS响应头
        response.setHeader("Access-Control-Allow-Origin", "http://example.com");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

        // 处理预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            // 正常处理请求
            response.getWriter().print("Data from server");
        }
    }
}

总结

根据你的技术栈和需求选择最适合的方式来配置CORS。

无论是通过注解、全局配置还是手动设置响应头,关键是确保你正确地指定了允许的来源、方法和其他必要的参数。

如果你使用的是Spring框架,特别是Spring Boot,推荐使用@CrossOrigin注解或全局配置的方式,因为它们更简洁且易于维护。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 巧妙的利用Mongodb做地理空间查询

    巧妙的利用Mongodb做地理空间查询

    本篇文章将会以Mongodb为数据库,讲述如何在数据库层级进行定位查询。具有很好的参考价值,下面跟着小编一起来看下吧
    2017-02-02
  • Spring AOP 的实现和切点表达式的实现方式

    Spring AOP 的实现和切点表达式的实现方式

    本文给大家介绍了Spring AOP的基本概念、通知类型、切点表达式和切面优先级,并通过示例代码展示了如何实现这些功能,感兴趣的朋友跟随小编一起看看吧
    2024-12-12
  • springboot集成nacos报错:get data from Nacos error,dataId:null.yaml的原因及解决方法

    springboot集成nacos报错:get data from Nacos 

    这篇文章给大家介绍了springboot集成nacos报错:get data from Nacos error,dataId:null.yaml的原因及解决方法,如果又遇到相同问题的朋友可以参考阅读本文
    2023-10-10
  • Java + Selenium + OpenCV解决自动化测试中的滑块验证问题

    Java + Selenium + OpenCV解决自动化测试中的滑块验证问题

    OpenCV是一个基于Apache2.0许可(开源)发行的跨平台计算机视觉和机器学习软件库,可以运行在Linux、Windows、Android和Mac OS操作系统上,这篇文章主要介绍了Java + Selenium + OpenCV解决自动化测试中的滑块验证,需要的朋友可以参考下
    2022-07-07
  • SpringMVC源码解读之HandlerMapping

    SpringMVC源码解读之HandlerMapping

    这篇文章主要介绍了SpringMVC源码解读之HandlerMapping 的相关资料,需要的朋友可以参考下
    2016-02-02
  • 告诉你springboot各个文件夹的作用

    告诉你springboot各个文件夹的作用

    这篇文章主要介绍了springboot各个文件夹是干嘛的,本文通过截图实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-08-08
  • 深入浅出理解Java泛型的使用

    深入浅出理解Java泛型的使用

    这篇文章主要介绍了深入浅出理解Java泛型的使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-09-09
  • 使用@Slf4j注解,log.info()无法使用问题

    使用@Slf4j注解,log.info()无法使用问题

    在使用Lombok的@Slf4j注解打印日志时遇到问题,通过降低Lombok版本(从1.18.x降至1.16.10)解决了问题
    2024-12-12
  • java抽象类和接口定义与用法详解

    java抽象类和接口定义与用法详解

    这篇文章主要介绍了java抽象类和接口定义与用法,结合实例形式详细分析了java抽象类和接口的基本概念、原理、定义、使用方法及操作注意事项,需要的朋友可以参考下
    2020-02-02
  • java代理实现爬取代理IP的示例

    java代理实现爬取代理IP的示例

    今天小编就为大家分享一篇java代理实现爬取代理IP的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05

最新评论