springboot解决跨域的四种姿势(代码片段)

author author     2022-12-03     412

关键词:

简介

跨域我就不多说了,我们今天开门见山直接解决跨域的几种姿势,那就上姿势

姿势

姿势一

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer 

    @Override
    public void addCorsMappings(CorsRegistry registry) 
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    

姿势二

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 CorsFilterConfig 


    /**
     * 开启跨域访问拦截器
     *
     * @date 2021/4/29 9:50
     */
    @Bean
    public CorsFilter corsFilter() 
        //创建CorsConfiguration对象后添加配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //设置放行哪些原始域
        corsConfiguration.addAllowedOrigin("*");
        //放行哪些原始请求头部信息
        corsConfiguration.addAllowedHeader("*");
        //放行哪些请求方式
        corsConfiguration.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //2. 添加映射路径
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    

姿势三

@Slf4j
@Component
@WebFilter(urlPatterns =  "/*" , filterName = "headerFilter")
public class HeaderFilter implements Filter 
    @Override
    public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException 
        HttpServletResponse response = (HttpServletResponse) resp;
        //解决跨域访问报错
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        //设置过期时间
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        // 支持HTTP 1.1.
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        // 支持HTTP 1.0. response.setHeader("Expires", "0");
        response.setHeader("Pragma", "no-cache");
        // 编码
        response.setCharacterEncoding("UTF-8");
        chain.doFilter(request, resp);
    

    @Override
    public void init(FilterConfig filterConfig) 
        log.info("跨域过滤器启动");
    

    @Override
    public void destroy() 
        log.info("跨域过滤器销毁");
    

姿势四

可以使用在单个方法上也可以使用在类上

Target(ElementType.TYPE, ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin 

	/** @deprecated as of Spring 5.0, in favor of @link CorsConfiguration#applyPermitDefaultValues */
	@Deprecated
	String[] DEFAULT_ORIGINS = "*";

	/** @deprecated as of Spring 5.0, in favor of @link CorsConfiguration#applyPermitDefaultValues */
	@Deprecated
	String[] DEFAULT_ALLOWED_HEADERS = "*";

	/** @deprecated as of Spring 5.0, in favor of @link CorsConfiguration#applyPermitDefaultValues */
	@Deprecated
	boolean DEFAULT_ALLOW_CREDENTIALS = false;

	/** @deprecated as of Spring 5.0, in favor of @link CorsConfiguration#applyPermitDefaultValues */
	@Deprecated
	long DEFAULT_MAX_AGE = 1800;


	/**
	 * Alias for @link #origins.
	 */
	@AliasFor("origins")
	String[] value() default ;

	/**
	 * A list of origins for which cross-origin requests are allowed. Please,
	 * see @link CorsConfiguration#setAllowedOrigins(List) for details.
	 * <p>By default all origins are allowed unless @code originPatterns is
	 * also set in which case @code originPatterns is used instead.
	 */
	@AliasFor("value")
	String[] origins() default ;

	/**
	 * Alternative to @link #origins() that supports origins declared via
	 * wildcard patterns. Please, see
	 * @link CorsConfiguration#setAllowedOriginPatterns(List) for details.
	 * <p>By default this is not set.
	 * @since 5.3
	 */
	String[] originPatterns() default ;

	/**
	 * The list of request headers that are permitted in actual requests,
	 * possibly @code "*"  to allow all headers.
	 * <p>Allowed headers are listed in the @code Access-Control-Allow-Headers
	 * response header of preflight requests.
	 * <p>A header name is not required to be listed if it is one of:
	 * @code Cache-Control, @code Content-Language, @code Expires,
	 * @code Last-Modified, or @code Pragma as per the CORS spec.
	 * <p>By default all requested headers are allowed.
	 */
	String[] allowedHeaders() default ;

	/**
	 * The List of response headers that the user-agent will allow the client
	 * to access on an actual response, other than "simple" headers, i.e.
	 * @code Cache-Control, @code Content-Language, @code Content-Type,
	 * @code Expires, @code Last-Modified, or @code Pragma,
	 * <p>Exposed headers are listed in the @code Access-Control-Expose-Headers
	 * response header of actual CORS requests.
	 * <p>The special value @code "*" allows all headers to be exposed for
	 * non-credentialed requests.
	 * <p>By default no headers are listed as exposed.
	 */
	String[] exposedHeaders() default ;

	/**
	 * The list of supported HTTP request methods.
	 * <p>By default the supported methods are the same as the ones to which a
	 * controller method is mapped.
	 */
	RequestMethod[] methods() default ;

	/**
	 * Whether the browser should send credentials, such as cookies along with
	 * cross domain requests, to the annotated endpoint. The configured value is
	 * set on the @code Access-Control-Allow-Credentials response header of
	 * preflight requests.
	 * <p><strong>NOTE:</strong> Be aware that this option establishes a high
	 * level of trust with the configured domains and also increases the surface
	 * attack of the web application by exposing sensitive user-specific
	 * information such as cookies and CSRF tokens.
	 * <p>By default this is not set in which case the
	 * @code Access-Control-Allow-Credentials header is also not set and
	 * credentials are therefore not allowed.
	 */
	String allowCredentials() default "";

	/**
	 * The maximum age (in seconds) of the cache duration for preflight responses.
	 * <p>This property controls the value of the @code Access-Control-Max-Age
	 * response header of preflight requests.
	 * <p>Setting this to a reasonable value can reduce the number of preflight
	 * request/response interactions required by the browser.
	 * A negative value means <em>undefined</em>.
	 * <p>By default this is set to @code 1800 seconds (30 minutes).
	 */
	long maxAge() default -1;

以上四种姿势都学会了么?学会了三连哦

可以关注公众号,学习更多的姿势

springboot的cros跨域问题经常始终不能解决跨域的原因(代码片段)

SpringBoot的Cros跨域问题经常始终不能解决跨域的原因问题问题的根本原因配置方法SpringBoot2.2.X版本SpringBoot2.5.X版本问题在配置跨域的@Configuration的时候,发现无论是.allowedOrigns()还是.allowedOriginParrtens()都解决不了的时候请看... 查看详情

springboot的cros跨域问题经常始终不能解决跨域的原因(代码片段)

SpringBoot的Cros跨域问题经常始终不能解决跨域的原因问题问题的根本原因配置方法SpringBoot2.2.X版本SpringBoot2.5.X版本问题在配置跨域的@Configuration的时候,发现无论是.allowedOrigns()还是.allowedOriginParrtens()都解决不了的时候请看... 查看详情

springboot处理跨域的正确姿势

好记忆不如烂笔头,能记下点东西,就记下点,有时间拿出来看看,也会发觉不一样的感受。目录1.概括2.错误姿势3.正确姿势1.概括跨域的问题经常出现,至于造成的原因,都知道,不多说。直接上干... 查看详情

解决springboot2.6和swagger冲突的四种方法(代码片段)

最近要将后台服务从SpringBoot1升级到2版本,主要目的是为了使用SpringBoot2的实时监控功能。集成的时候无法启动,根据日志判断与swagger有关。信息如下:org.springframework.context.ApplicationContextException:Failedtostartbean'docume... 查看详情

一文搞懂│什么是跨域?如何解决跨域?(代码片段)

✨目录🎈什么是跨域🎈跨域场景🎈解决跨域的四种方式🎈什么是跨域域:是指浏览器不能执行其他网站的脚本跨域:它是由浏览器的同源策略造成的,是浏览器对JavaScript实施的安全限制,所谓同源... 查看详情

解决跨域问题,实例调用百度地图(代码片段)

...的同源是指,域名、协议、端口均为相同。前端常见跨域解决方案(全)当年那些风骚的跨域操作全解跨域请求处理办法不要再问我跨域的问题了九种“姿势”让你彻底解决跨域问题2.如何解决跨域?JSONP: 查看详情

springboot的cros跨域问题经常始终不能解决跨域的原因

SpringBoot的Cros跨域问题经常始终不能解决跨域的原因问题问题的根本原因配置方法SpringBoot2.2.X版本SpringBoot2.5.X版本问题在配置跨域的@Configuration的时候,发现无论是.allowedOrigns()还是.allowedOriginParrtens()都解决不了的时候请看... 查看详情

springboot:配置解决跨域请求(代码片段)

springboot解决跨域的方式有多种,此文用的是通过增加配置类来解决跨域。项目中增加配置类:CorsConfig.javapackagecom.yych.zyysys.config.cors;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importo... 查看详情

springboot配置cors跨域的几种方法(代码片段)

作记录用请参考https://blog.csdn.net/lizc_lizc/article/details/81155895 第一种:  在每个controller上添加 @CrossOrigin第二种:使用拦截器  1、方法一@ConfigurationpublicclassCorsConfig@BeanpublicCorsFiltercorsFilter()final 查看详情

springboot跨域问题解决方案(代码片段)

...根据自己需要修改以下就可以解决跨域问题啦packagecom.el.springboot.config;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.cors.CorsConfiguration;importorg.springframework.web.cors.UrlBasedCor... 查看详情

springboot跨域解决方案(代码片段)

1:为什么会出现跨域问题  出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。... 查看详情

springboot跨域解决方案(代码片段)

1:为什么会出现跨域问题  出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。... 查看详情

相关前台跨域的解决方式(代码片段)

title:前端跨域处理方式date:2018-07-0800:37:29categories:Web前端tags:跨域cors关于跨域请求解觉方案问题关于浏览器跨域问题,项目中也遇到了,看了项目上一些代码的处理方式,感觉存在不少不大完善的地方,因此对于跨域,想好好梳... 查看详情

解决springboot跨域的三种方式

原文链接: https://3water.com/article/cMTM39MjMzdLmY5一、什么是跨域1.1、为什么会出现跨域问题出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏... 查看详情

解决cors跨域的filter(代码片段)

importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.core.Ordered;importjavax.servlet.*;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/***desc:**@aut 查看详情

springboot中实现跨域的5种方式(代码片段)

对于CORS的跨域请求,主要有以下几种方式可供选择:1、返回新的CorsFilter(全局跨域)packagecom.cfit.framework.config;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.cors.Cor... 查看详情

springboot解决全局和局部跨域问题的两种方式(代码片段)

前言在如今前后端分离的开发模式下,跨域是一个非常经典的问题,解决的方式也有很多,比如代理服务器,使用JSONP我之前也写过一篇解决跨域问题的文章,感兴趣的可以参考:解决Vue前后端跨域问题的... 查看详情

springboot——thymeleaf中的四种字面量(文本数字布尔null)字符串拼接运算符(代码片段)

1.四种字面量首先写一个User类、以及控制层UserController类,其中有一个请求方法。packagecom.songzihao.springboot.model;/****/publicclassUserprivateIntegerid;privateStringusername;//getterandsetterpackagecom.songzihao.spring 查看详情