Spring之跨域资源共享(CORS)

CORS允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。
整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。
因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信

使用spring对跨域的支持非常简单:

直接在方法级别添加@CrossOrigin.(局部配置)

默认情况下@CrossOrigin允许:

①所有的起源。

②所有标题。

③控制器方法映射到的所有HTTP方法。

④allowedCredentials 默认情况下不启用,因为它建立了一个信任级别,暴露敏感的用户特定信息,如cookie和CSRF令牌,并且只能在适当的时候使用。

⑤maxAge 设置为30分钟。

@CrossOrigin 也在类级别上得到支持,并通过所有方法继承:

@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

CrossOrigin 可以在类和方法级别使用:

@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin("http://domain2.com")
    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

全局配置

单独设置一个配置类:

package com.example.demo.config;

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;

/**
 * CORS(跨域请求的总配置类)
 *
 * @author Lframe
 * @create2018 -05 -05 -23:39
 */
@Configuration
public class CORSconfigurer {

    @Bean
    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                //registry允许设置多个。
                registry
                        .addMapping("/lframe") //允许的映射
                        .allowedMethods("GET")  //允许的方法
                        .allowedOrigins("http://localhost:63343");  //允许的IP
                registry.addMapping("/get/people")
                        .allowedMethods("POST")
                        .allowedOrigins("http://localhost:63343");

            }

        };
    }
}

控制器:

package com.example.demo.controller;

import com.example.demo.domain.People;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Lframe
 * @create2018 -05 -05 -23:33
 */
@RestController
@Slf4j
public class PostAjaxController {

    @GetMapping("/lframe")
    public String test(){
        return "success";
    }

    @PostMapping("/get/people")
    public People gerPeople(People people){
        log.info("上传上来的信息:{}",people);
        return people;
    }
}

people类:(其中的@Data是lombok的注解)

package com.example.demo.domain;

import lombok.Data;

/**
 * @author Lframe
 * @create2018 -05 -06 -9:23
 */
@Data
public class People {
    private String name;
    private Integer age;
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

前端的post的ajax请求:

<!DOCTYPE html>
<html lang="en">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        <!--下面这个是ajax的post方法-->
        $(function () {
            var page = "http://localhost:8081/get/people";
            $("#sb").click(function () {
                $.post(
                    page,
                    {"name": "lframe", "age": 11},
                    function (result) {
                        console.log(result.age);
                    }
                )
            })
        })
    </script>
</head>
<body>
<button id="lframe">点击</button>
<button id="sb">上传内容</button>
<p id="first"></p>
</body>
</html>
<script src="AjaxGetTest.js"></script>

前端的GET ajax请求:

var page = “http://localhost:8081/lframe“;
//下面这个是ajax的get方式
(function () { .get(
page,
function (result) {
if (result==”success”){
alert(result);
}
}
)
});

总的来说,spring对CORS的支持非常丰富,而且配置起来非常简单,如果对AJAX不熟悉的话,可以上网上查查资料,学习一下。

猜你喜欢

转载自blog.csdn.net/m0_37884977/article/details/80212220