springboot解决跨域的几种方式

跨域简介:

        当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。只有前端请求后端(比如ajax)才会出现跨域,后端请求其他源后端(比如resttemplete,httpclient)虽然不同源,但是不会出现跨域

方法一、SpringBoot的注解@CrossOrigin

直接在Controller方法或者类上增加@CrossOrigin注解,SpringMVC使用@CrossOrigin使用场景要求 jdk1.8+ Spring4.2+

@GetMapping("/hello")
@CrossOrigin
public String hello() {
        return "hello:" + simpleDateFormat.format(new Date());
}

方式二:使用CorsFilter

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;

@Configuration
public class ConfigConfiguration {

    @Bean
    public CorsFilter CorsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource ub = new UrlBasedCorsConfigurationSource();
        ub.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsFilter(ub);
    }
}

security项目可以不用 CorsFilter :

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //忽略hellopost接口
        http.csrf().disable();

        http.authorizeRequests()
                .antMatchers("/hello", "/loginalert", "/mylogin").permitAll()
                .antMatchers("/helloadmin").hasRole("admin")
                .antMatchers("/hellouser").hasAuthority("query")
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/mylogin.html")
                .usernameParameter("uname").passwordParameter("passwd")
                .permitAll();
							
		http.cors().configurationSource(corsConfigurationSource());
    }

    public CorsConfigurationSource corsConfigurationSource(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource ub = new UrlBasedCorsConfigurationSource();
        ub.registerCorsConfiguration("/**", corsConfiguration);
        return ub;
    }
}

方式三:自定义过滤(web  filter)的方式

@Component
public class CustomFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        // 设置允许Cookie
        res.addHeader("Access-Control-Allow-Credentials", "true");
        // 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求
        res.addHeader("Access-Control-Allow-Origin", "*");
        // 设置允许跨域请求的方法
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        // 允许跨域请求包含content-type
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (((HttpServletRequest) servletRequest).getMethod().equals("OPTIONS")) {
            servletResponse.getWriter().println("ok");
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

 方式四:实现WebMvcConfigurer中addCorsMappings方法

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 匹配所有的路径
                .allowCredentials(true) // 设置允许凭证
                .allowedHeaders("*")   // 设置请求头
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 设置允许的方式
                .allowedOriginPatterns("*");
    }
}

 方法五:采用nginx做动态代理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值