springboot解决ajax跨域问题

文章介绍了在Spring中处理跨域请求的五种方法:1)使用@CrossOrigin注解在类或方法上;2)配置文件中自定义CorsConfig实现全局跨域;3)创建CorsFilter处理跨域;4)添加请求头Access-Control-Allow-Origin;5)JSONP方式。这些方法帮助开发者解决前后端跨域通信的问题。
摘要由CSDN通过智能技术生成

方式1:使用@CrossOrigin注解方式

@CrossOrigin(origins = "*") //解决跨域的关键注解,该注解可以标注在类上也可以标注在方法上

域A:http://localhost/across_test/test.html

域A下的test.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./jquery.js"></script>
</head>
<body>

<button id="btn">测试ajax跨域请求</button>

<script>
    $("#btn").click(function () {
        $.ajax({
            type: "get",
            url: "http://localhost:8080/cros_demo",
            success: function (json) {
                console.log(json)
            },
            error: function () {
                alert('fail');
            }
        });
    });
</script>

</body>
</html>

域B:http://localhost:8080/cros_demo

域B下的HelloController.java

@CrossOrigin注解标注在类上

package com.example.controller;

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

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
@CrossOrigin(origins = "*") //解决跨域的关键注解,方式一:标注在类上
public class HelloController {

    @RequestMapping("/cros_demo")
    public HashMap<Integer, String> crosDemo(HttpServletResponse response) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Shanghai");
        map.put(2, "Beijing");
        return map;
    }
}

@CrossOrigin注解标注在方法上

package com.example.controller;

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

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
public class HelloController {

    @RequestMapping("/cros_demo")
    @CrossOrigin(origins = "*") //解决跨域的关键注解,方式二:标注在方法上
    public HashMap<Integer, String> crosDemo(HttpServletResponse response) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Shanghai");
        map.put(2, "Beijing");
        return map;
    }
}

效果:

在这里插入图片描述

方式2: 配置文件解决全局跨域问题

编写配置文件自定义CorsConfig.java

CorsConfig.java
package com.example.cros;

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 CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST")
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}
HelloController.java
package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
public class HelloController {

    @RequestMapping("/cros_demo")
    public HashMap<Integer, String> crosDemo(HttpServletResponse response) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Shanghai");
        map.put(2, "Beijing");
        return map;
    }
}

效果如下:

在这里插入图片描述

方式3: 通过 CorsFilter 跨域

MyCorsFilter.java
package com.example.cros;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class MyCorsFilter {
    @Bean
    public CorsFilter corsFilter() {
        // 1.创建 CORS 配置对象
        CorsConfiguration config = new CorsConfiguration();
        // 支持域
        config.addAllowedOriginPattern("*");
        // 是否发送 Cookie
        config.setAllowCredentials(true);
        // 支持请求方式
        config.addAllowedMethod("*");
        // 允许的原始请求头部信息
        config.addAllowedHeader("*");
        // 暴露的头部信息
        config.addExposedHeader("*");
        // 2.添加地址映射
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        // 3.返回 CorsFilter 对象
        return new CorsFilter(corsConfigurationSource);
    }
}
HelloController.java
package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
public class HelloController {

    @RequestMapping("/cros_demo")
    public HashMap<Integer, String> crosDemo(HttpServletResponse response) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Shanghai");
        map.put(2, "Beijing");
        return map;
    }
}

效果:

在这里插入图片描述

方式4: 添加请求头方式

添加请求头: Access-Control-Allow-Origin

HelloController.java
package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
public class HelloController {

    @RequestMapping("/cros_demo")
    public HashMap<Integer, String> crosDemo(HttpServletResponse response) {
        // 设置跨域
        response.setHeader("Access-Control-Allow-Origin", "*");

        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Shanghai");
        map.put(2, "Beijing");
        return map;
    }
}

效果:

在这里插入图片描述

方式5: jsonp方式

省略,参考: https://blog.csdn.net/shj_php/article/details/130128484

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值