spring-boot 允許接口跨域并實現(xiàn)攔截(CORS)

pom.xml(依賴的jar)
// 在spring-boot-starter-web的啟動器中,已經(jīng)依賴好了
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
</dependency>
CORS跨域的配置(主要配置允許什么樣的方法跨域)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Msater Zg on 2017/4/3.
 */
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        List<String> list = new ArrayList<>();
        list.add("*");
        corsConfiguration.setAllowedOrigins(list);
        /*
        // 請求常用的三種配置,*代表允許所有,當時你也可以自定義屬性(比如header只能帶什么,只能是post方式等等)
        */
        corsConfiguration.addAllowedOrigin("*");  
        corsConfiguration.addAllowedHeader("*"); 
        corsConfiguration.addAllowedMethod("*");  
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}
攔截器配置(可以根據(jù)不同路徑,配置不同的攔截器)
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by Msater Zg on 2017/4/5.
 * 攔截器
 */
public class ApiInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 請求前調(diào)用
        System.out.println("攔截了");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 請求過程中調(diào)用
        System.out.println("攔截了");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 請求完成時調(diào)用
        System.out.println("攔截了");
    }
}
攔截器管理類,用于生成項目的攔截器鏈
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * Created by Msater Zg on 2017/4/5.
 * 攔截器管理工具
 */
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多個攔截器組成一個攔截器鏈
        // addPathPatterns 用于添加攔截規(guī)則
        // excludePathPatterns 用戶排除攔截
        registry.addInterceptor(new ApiInterceptor()).addPathPatterns("/user/**");  //對來自/user/** 這個鏈接來的請求進行攔截
        super.addInterceptors(registry);
    }
}
結(jié)語

實現(xiàn)跨域的方式有很多,這只是其中一種。有什么不對的地方希望能及時指出。謝謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,696評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,288評論 6 342
  • 前言:眾所周知,出于安全考慮,XMLHttpReqeust 對象發(fā)起的 HTTP 請求必須滿足同源策略(same-...
    ken_ljq閱讀 29,906評論 2 20
  • 1.“去偽存真” 為了做好一件事,我們會做很多努力。但是很多時候我們發(fā)現(xiàn)做的時間越長,卻偏離了做事的初衷和軌跡。比...
    鯨魚我愛你閱讀 237評論 0 3
  • 無權(quán)無勢而受人尊敬 無名無姓而被人欣賞 無色無相而得人愛慕 這大約就是真正的成功了
    真小實閱讀 620評論 14 10

友情鏈接更多精彩內(nèi)容