CORS(服务器端技术)

CORS跨域访问说明

2.1CORS说明

CORS,全称Cross-Origin Resource Sharing [1] ,是一种允许当前域(domain)的资源(比如html/js/web service)被其他域(domain)的脚本请求访问的机制,通常由于同域安全策略(the same-origin security policy)浏览器会禁止这种跨域请求。
知识回顾:
JSONP: 用户利用jsonp向服务器端动态获取数据的过程. 主体用户.
CORS: 服务器是否允许客户端访问的技术. 主体服务器.

2.2 CORS原理说明

用户可以向普通的ajax请求一样发起跨域请求. get/post/put/delete,由于当下的跨域的业务比较常见,所有的主流的浏览器默认支持跨域. CORS核心需要配置服务器端是否允许跨域

编辑CORS跨域

说明:为了以后能够实现通用,则在jt-common中添加cors操作.

package com.jt.config;

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) {
        //1.允许什么样的请求进行跨域
        // /* 只允许一级目录请求    /** 表示多级目录请求.
        registry.addMapping("/**")
        //2.允许哪些服务进行跨域
                .allowedOrigins("*")
                //3.是否允许携带cookie信息
                .allowCredentials(true)
                //4.定义探针检测时间 在规定的时间内不再询问是否允许跨域
                .maxAge(1800);
    }
}

 

package com.jt.controller;

import com.jt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//服务器端程序要求返回的都是JSON 所以使用
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /*demo测试*/
    @RequestMapping("/getMsg")
    public String  getMsg(){

        return "sso单点登录系统正常";
    }
}
原文地址:https://www.cnblogs.com/wangjincai/p/13525916.html