栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

浅谈spring-boot 允许接口跨域并实现拦截(CORS)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

浅谈spring-boot 允许接口跨域并实现拦截(CORS)

本文介绍了spring-boot 允许接口跨域并实现拦截(CORS),分享给大家,也给自己留个笔记

pom.xml(依赖的jar)

// 在spring-boot-starter-web的启动器中,已经依赖好了

      org.springframework.boot
      spring-boot-starter-web

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;

@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("
    corsConfiguration.addAllowedOrigin("*"); 
    corsConfiguration.addAllowedHeader("*"); 
    corsConfiguration.addAllowedMethod("*"); 
    return corsConfiguration;
  }
  @Bean
  public CorsFilter corsFilter() {
    UrlbasedCorsConfigurationSource source = new UrlbasedCorsConfigurationSource();
    source.registerCorsConfiguration("
public class ApiInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // 请求前调用
    System.out.println("拦截了");
    return true;
  }
  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    // 请求过程中调用
    System.out.println("拦截了");
  }
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    // 请求完成时调用
    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;

@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 多个拦截器组成一个拦截器链
    // addPathPatterns 用于添加拦截规则
    // excludePathPatterns 用户排除拦截
    registry.addInterceptor(new ApiInterceptor()).addPathPatterns("/user/**"); //对来自/user/** 这个链接来的请求进行拦截
    super.addInterceptors(registry);
  }
}

结语

实现跨域的方式有很多,这只是其中一种。有什么不对的地方希望能及时指出。谢谢!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/144761.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号