springBoot(9):web開發-CORS支持

1、簡介java

Web 開發常常會遇到跨域問題,解決方案有:jsonp,iframe,CORS 等等web

1.一、CORS與JSONP相比spring

一、JSONP只能實現GET請求,而CORS支持全部類型的HTTP請求。json

二、使用CORS,開發者能夠使用普通的XMLHttpRequest發起請求和得到數據,比起JSONP 有更好的錯誤處理。api

三、JSONP主要被老的瀏覽器支持,它們每每不支持CORS,而絕大多數現代瀏覽器都已經支持了CORS瀏覽器支持狀況跨域

  Chrome 3+瀏覽器

  Firefox 3.5+app

  Opera 12+cors

  Safari 4+ide

  Internet Explorer 8+

2、實現CORS

說明:在springMVC中能夠配置全局的規則,也能夠使用@CrossOrigin註解進行細粒度的配置

2.一、全局配置

方式一:註冊bean

package com.example.demo.utils.configuration;

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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by DELL on 2017/6/18.
 */
@Configuration
public class CustomCorsConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
            }
        };
    }
}

說明:表示對於/api請求下的因此資源,容許http://localhost:8080訪問

方式二:繼承WebMvcConfigurerAdapter

package com.example.demo.utils.configuration;

import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 跨域請求處理
 * @Author: 我愛大金子
 * @Description: 跨域請求處理
 * @Date: Created in 10:12 2017/6/18
 */
@Configuration
public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
    }
}

說明:表示對於/api請求下的因此資源,容許http://localhost:8080訪問


2.二、細粒度配置

在controller中加入@CrossOrigin註解,如:@CrossOrigin(origins = "http://localhost:8080")

wKiom1lF6bXzHTE0AACZlc9X59I860.png

相關文章
相關標籤/搜索