SpringBoot解决CORS跨域(@CrossOrigin)

SpringBoot解决CORS跨域@CrossOrigin使用

在某个类上添加@CrossOrigin 注解时 origins 属性

package com.example.demo.controller;

import com.example.demo.domain.User;
import com.example.demo.service.IUserFind;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Title: UserController
 * @ProjectName demo
 * @Description: 请求处理控制器
 * @author 浅然
 * @date 2018/7/2022:18
**/
@RestController
//实现跨域注解
//origin="*"代表所有域名都可访问
//maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒
//若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失
@CrossOrigin(origins = "*",maxAge = 3600)
public class UserController {
    @Resource
    private IUserFind userFind;

    @GetMapping("finduser")
    public User finduser(@RequestParam(value="id") Integer id){
        //此处省略相应代码
    }
}

在某个方法上添加@CrossOrigin 注解时 origins 属性一定要写ip号 如果输入localhost有时会出现403错误

package com.example.demo.controller;

import com.example.demo.domain.User;
import com.example.demo.service.IUserFind;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Title: UserController
 * @ProjectName demo
 * @Description: 请求处理控制器
 * @author 浅然
 * @date 2018/7/2022:18
**/
@RestController
//实现跨域注解
//origin="*"代表所有域名都可访问
//maxAge飞行前响应的缓存持续时间的最大年龄,简单来说就是Cookie的有效期 单位为秒
//若maxAge是负数,则代表为临时Cookie,不会被持久化,Cookie信息保存在浏览器内存中,浏览器关闭Cookie就消失
@CrossOrigin(origins = "*",maxAge = 3600)
public class UserController {
    @Resource
    private IUserFind userFind;

    @GetMapping("finduser")
    public User finduser(@RequestParam(value="id") Integer id){
        //此处省略相应代码
    }
}

 

posted @ 2021-07-26 15:13  哈尔的卡西法  阅读(557)  评论(0)    收藏  举报