Spring Boot使用CORS解决跨域问题

一、跨域问题描述

Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等。
CORS 与 JSONP 相比:
1、 JSONP 只能实现 GET 请求,而 CORS 支持所有类型的 HTTP 请求。
2、 使用 CORS,开发者可以使用普通的 XMLHttpRequest 发起请求和获得数据,比起 JSONP 有更好的 错误处理。
3、 JSONP 主要被老的浏览器支持,它们往往不支持 CORS,而绝大多数现代浏览器都已经支持了 CORS。

二、CORS常用的三种解决跨域问题的方法

这里我仅仅写出一个需要被跨域访问的方法,提出了三种解决方案。
需要被跨域访问的方法:

package com.lemon.springboot.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lemon
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

    // @CrossOrigin({"http://localhost:8081", "http://localhost:8082"})
    @RequestMapping("/get")
    public Map<String, Object> get(@RequestParam String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("title", "hello world");
        map.put("name", name);
        return map;
    }
}
1、配置全局跨域访问解决方案

写一个配置类,指定可以被跨域访问的路径以及可以跨域的主机链接。这样,8081和8082端口的应用就可以访问/api后所有的方法或者资源。

package com.lemon.springboot.configuration;

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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 全局配置跨域问题
 * @author lemon
 */
@Configuration
public class CustomCorsConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {

        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                // 设置了可以被跨域访问的路径和可以被哪些主机跨域访问
                registry.addMapping("/api/**").allowedOrigins("http://localhost:8081", "http://localhost:8082");
            }
        };
    }
}
2、第二种全局设置方法
package com.lemon.springboot.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author lemon
 */
@Configuration
public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置了可以被跨域访问的路径和可以被哪些主机跨域访问
        registry.addMapping("/api/**").allowedOrigins("http://localhost:8081", "http://localhost:8082");
    }
}
3、使用@CrossOrigin注解实现细粒度控制(推荐使用)

直接在需要被跨域访问的方法上加上@CrossOrigin注解就可以实现被跨域访问。

package com.lemon.springboot.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lemon
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

    @CrossOrigin({"http://localhost:8081", "http://localhost:8082"})
    @RequestMapping("/get")
    public Map<String, Object> get(@RequestParam String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("title", "hello world");
        map.put("name", name);
        return map;
    }
}

这三种配置方法,当其他系统内的资源跨域访问的时候,就会起作用!

更多干货分享,欢迎关注我的微信公众号:爪哇论剑(微信号:itlemon)
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值