解决跨域问题之Spring框架

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq360694660/article/details/81633188

JSONP也好,还是CORS也好,是可以解决跨域问题的通用方案。

如果应用中使用了Spring框架,那么服务端支持跨域就简单一匹

只需在对应的Controller中使用注解@CrossOrigin。

package com.example.studySpringBoot.controller;

import com.example.studySpringBoot.entity.People;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@CrossOrigin // 支持跨域
public class HelloWordController {

    @Autowired
    private People people;

    @RequestMapping("/sayHi")
    public String sayHelloWord() {
        return "Hello word SpringBoot";
    }

    @RequestMapping("/who")
    public String getPeople(){
        return people.toString();
    }

}

@CrossOrigin注解介绍:

1、该注解可以使用在类上和方法上。

2、支持所有域,所有自定义头,并且支持携带Cookie,options预计请求的有效时间默认是1800S

猜你喜欢

转载自blog.csdn.net/qq360694660/article/details/81633188
今日推荐