1. 程式人生 > >解決跨域問題之Spring框架

解決跨域問題之Spring框架

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