SpringBoot: 全局跨域配置

时间:2025-02-22 14:23:23

一、可以在配置类中通过配置一个@Bean,直接实现全局的跨域,不需要在每个controller上加@CrossOrigin注解了。

package ;

import ;
import ;
import ;
import ;
@Configuration(proxyBeanMethods = false)
public class MyCorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                ("/**");
            }
        };
    }


}

二、适用情况:
1、返回字符串或对象的接口

    @RequestMapping("/getRate")
    public String getRate(){
        return "rate...";
    }

2.通过ResponseEntity提供文件下载功能的接口

    @RequestMapping(value="/get/csv")
    public ResponseEntity<byte[]> download(HttpServletRequest request)throws Exception{
        String content="first,second,third";
         builder = ();
        (());
        (MediaType.APPLICATION_OCTET_STREAM);
        String fileName = ("", "UTF-8");
        ("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        return (());
    }

三、不适用的情况:直接适用HttpServletResponse进行内容返回的接口。需要将注释的部分打开才能跨域

    @RequestMapping("/get/csv2")
    public void getCSV2(HttpServletResponse response) {

        String resultString="first,second,third";
        byte[] bytes = ();
        ();// 清空输出流
        ("application/x-download");
        ("UTF-8");
        ("Content-Disposition", "attachment;filename=" + "test" + ".csv");

/*        ("Access-Control-Allow-Origin", "*");
        ("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        ("Access-Control-Max-Age", "9600");
        ("Access-Control-Allow-Headers", "x-requested-with");*/


        try {
            OutputStream os = ();
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ("Content-Length", (()));
            byte[] b = new byte[1024];
            while (((b)) > 0) {
                (b);
            }
            ();
            ();
            ();
        } catch (Exception ex) {
            (());
        }
    }