欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java后端配置允許跨域方式

 更新時(shí)間:2025年02月06日 09:33:28   作者:白天睡晚上卷  
本文介紹了在不同技術(shù)和框架中配置跨域資源共享(CORS)的方法,包括使用SpringMVC的@CrossOrigin注解、SpringBoot的全局CORS配置、SpringSecurity中的CORS集成以及手動(dòng)設(shè)置響應(yīng)頭,根據(jù)具體需求和技術(shù)棧,選擇合適的方法來(lái)確??缬蛘?qǐng)求的安全性和有效性

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

如果你使用的是Spring MVC或Spring Boot,最簡(jiǎn)單的方法是直接在控制器類(lèi)或方法上使用@CrossOrigin注解來(lái)允許特定來(lái)源的跨域請(qǐng)求。

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") // 允許來(lái)自example.com的跨域請(qǐng)求
public class MyController {

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

你可以指定多個(gè)來(lái)源,或者使用*來(lái)允許所有來(lái)源(但不推薦用于生產(chǎn)環(huán)境):

@CrossOrigin(origins = "*") // 允許所有來(lái)源

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

為了在整個(gè)應(yīng)用程序中統(tǒng)一配置CORS規(guī)則,而不是逐個(gè)控制器或方法進(jìn)行配置,可以通過(guò)實(shí)現(xiàn)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("/**") // 應(yīng)用于所有路徑
                    .allowedOrigins("http://example.com") // 允許的來(lái)源
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允許的方法
                    .allowCredentials(true) // 是否允許發(fā)送憑證信息(如Cookies)
                    .maxAge(3600); // 預(yù)檢請(qǐng)求的有效期(秒)
            }
        };
    }
}

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

如果你的應(yīng)用程序使用了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(); // 根據(jù)需要啟用或禁用CSRF保護(hù)
    }

    @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. 手動(dòng)設(shè)置響應(yīng)頭 (Servlet API)

對(duì)于不使用Spring框架的項(xiàng)目,可以在Servlet中手動(dòng)設(shè)置響應(yīng)頭來(lái)允許跨域請(qǐng)求。

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 {
        
        // 設(shè)置CORS響應(yīng)頭
        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");

        // 處理預(yù)檢請(qǐng)求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            // 正常處理請(qǐng)求
            response.getWriter().print("Data from server");
        }
    }
}

總結(jié)

根據(jù)你的技術(shù)棧和需求選擇最適合的方式來(lái)配置CORS。

無(wú)論是通過(guò)注解、全局配置還是手動(dòng)設(shè)置響應(yīng)頭,關(guān)鍵是確保你正確地指定了允許的來(lái)源、方法和其他必要的參數(shù)。

如果你使用的是Spring框架,特別是Spring Boot,推薦使用@CrossOrigin注解或全局配置的方式,因?yàn)樗鼈兏?jiǎn)潔且易于維護(hù)。

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java中的Calendar日歷API用法完全解析

    Java中的Calendar日歷API用法完全解析

    今天特別整理了針對(duì)Java中的Calendar日歷API用法完全解析,通過(guò)Calendar API我們可以對(duì)Calendar所提供的時(shí)間日期字段進(jìn)行各種自定義操作,首先還是從Calendar的基礎(chǔ)入手:
    2016-06-06
  • Java實(shí)現(xiàn)分頁(yè)的幾種方法詳細(xì)解析

    Java實(shí)現(xiàn)分頁(yè)的幾種方法詳細(xì)解析

    這篇文章主要介紹了Java實(shí)現(xiàn)分頁(yè)的幾種方法詳細(xì)解析,在Java中想實(shí)現(xiàn)分頁(yè)功能有幾種常用的方法,今天我們就來(lái)詳細(xì)解析一下,文中提供了解決思路和部分實(shí)現(xiàn)代碼,需要的朋友可以參考下
    2023-11-11
  • idea安裝jerbel及文件上傳下載的實(shí)現(xiàn)示例

    idea安裝jerbel及文件上傳下載的實(shí)現(xiàn)示例

    JRebel是一個(gè)Java開(kāi)發(fā)工具,它是一款用于實(shí)時(shí)代碼重載的插件,本文主要介紹了idea安裝jerbel及文件上傳下載的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解下
    2023-09-09
  • App登陸java后臺(tái)處理和用戶(hù)權(quán)限驗(yàn)證

    App登陸java后臺(tái)處理和用戶(hù)權(quán)限驗(yàn)證

    這篇文章主要為大家詳細(xì)介紹了App登陸java后臺(tái)處理和用戶(hù)權(quán)限驗(yàn)證,感興趣的朋友可以參考一下
    2016-06-06
  • Python基礎(chǔ)之如何使用multiprocessing模塊

    Python基礎(chǔ)之如何使用multiprocessing模塊

    今天帶大家學(xué)習(xí)python多進(jìn)程的相關(guān)知識(shí),文中對(duì)multiprocessing模塊的使用作了非常詳細(xì)的介紹,需要的朋友可以參考下
    2021-06-06
  • mybatis自動(dòng)生成時(shí)如何設(shè)置不生成Example類(lèi)詳解

    mybatis自動(dòng)生成時(shí)如何設(shè)置不生成Example類(lèi)詳解

    這篇文章主要給大家介紹了關(guān)于mybatis自動(dòng)生成時(shí)如何設(shè)置不生成Example類(lèi)的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。
    2017-05-05
  • 使用Spring AntPathMatcher的doMatch方法

    使用Spring AntPathMatcher的doMatch方法

    這篇文章主要介紹了使用Spring AntPathMatcher的doMatch方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Mybatis解決找不到get方法

    Mybatis解決找不到get方法

    這篇文章主要介紹了Mybatis解決找不到get方法問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • java實(shí)現(xiàn)PPT轉(zhuǎn)化為PDF

    java實(shí)現(xiàn)PPT轉(zhuǎn)化為PDF

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)PPT轉(zhuǎn)化為PDF的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • Maven中央倉(cāng)庫(kù)地址配置大全

    Maven中央倉(cāng)庫(kù)地址配置大全

    這篇文章主要介紹了Maven中央倉(cāng)庫(kù)地址配置大全,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06

最新評(píng)論