美文网首页
springBoot跨域三种方式

springBoot跨域三种方式

作者: IT小池 | 来源:发表于2020-04-05 15:48 被阅读0次

    说不上那种好,我之前一直使用的是第三种方式进行跨域,没问题,但是在我结合 Shiro 后,第三种方式没用,于是有了第一种、第二种方式,这里 我使用的是第一种方式,由于浏览器复杂请求会先发出一个 OPTIONS 请求,然后在执行请求接口,我使用第二种方式跨域,在拦截方法里会进入2此该拦截方法,我有点小强迫症,于是找到了第一种方式,仅供参考。

    1.CorsConfig

    创建配置类 CorsConfig.java

    package com.shiro.config;
    
    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 CorsConfig {
    
        private CorsConfiguration buildConfig() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.addAllowedOrigin("*");
            corsConfiguration.addAllowedHeader("*");
            corsConfiguration.addAllowedMethod("*");
            corsConfiguration.setMaxAge(3600L);         // 预检请求的有效期,单位为秒。
            corsConfiguration.setAllowCredentials(true);// 是否支持安全证书(必需参数)
            return corsConfiguration;
        }
        @Bean
        public CorsFilter corsFilter(){
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", buildConfig());
            return new CorsFilter(source);
        }
    }
    

    OK,直接就可以访问了

    2.CrossOriginFilter

    创建 CrossOriginFilter.java

    package com.shiro.shiro;
    
    import org.springframework.beans.factory.annotation.Value;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    
    public class CrossOriginFilter implements Filter {
    
        @Value("${cors.origin}") // *
        private String origin;
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            httpResponse.setHeader("Access-Control-Allow-Origin", origin);
            httpResponse.setHeader("Access-Control-Allow-Methods", httpRequest.getMethod());
            httpResponse.setHeader("Access-Control-Max-Age", "3600");
            httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
            chain.doFilter(request, response);
        }
    }
    

    然后在 springboot 启动类中加入如下:

    package com.shiro;
    
    import com.shiro.shiro.CrossOriginFilter;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    
    @MapperScan(value = "com.shiro.dao")
    @SpringBootApplication
    public class SpringbootShiroApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringbootShiroApplication.class, args);
        }
    
        @Bean
        public CrossOriginFilter crossOriginFilter(){
            return new CrossOriginFilter();
        }
    
        @Bean
        public FilterRegistrationBean getFilterRegistrationBean(){
            FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
            /**
             * 设置过滤器
             */
            filterRegistrationBean.setFilter(crossOriginFilter());
            /**
             * 拦截路径
             */
            filterRegistrationBean.addUrlPatterns("/api/*");
            /**
             * 设置名称
             */
            filterRegistrationBean.setName("CrossOriginFilter");
    
            return filterRegistrationBean;
        }
    }
    

    3.WebMvcConfig

    创建配置类 WebMvcConfig.java

    package com.shiro.config;
    
    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 WebMvcConfig implements WebMvcConfigurer {
        /**
         * 跨域
         * @param registry
         */
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/*/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET","POST","PUT","DELETE","OPTIONS") // 真实请求允许的方法
                    .allowedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "authorization") // 服务器允许使用的字段
                    .allowCredentials(true) // 是否允许用户发送、处理 cookie
                    .maxAge(3600); // 预检请求的有效期,单位为秒。有效期内,不会重复发送预检请求
        }
    }
    

    相关文章

      网友评论

          本文标题:springBoot跨域三种方式

          本文链接:https://www.haomeiwen.com/subject/kfbuphtx.html