springboot解决跨域问题

springboot框架解决方法


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("*"); 
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source= new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); 
        return new CorsFilter(source);
    }

传统框架解决方法:


public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,
            ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    
//      httpResponse.addHeader("Access-Control-Allow-Origin", "http://eka-wx.eka-medical.com");      
//      httpResponse.addHeader("Access-Control-Allow-Origin", "http://eka-wx.lightuni.cn");
//      httpResponse.addHeader("Access-Control-Allow-Origin", "http://eka.ouryou.cn");
        String url = httpRequest.getHeader("Origin");
        if(url != null && url.contains("http")){
            httpResponse.addHeader("Access-Control-Allow-Origin", url); 
        }else{
            httpResponse.addHeader("Access-Control-Allow-Origin", "http://eka-wx.eka-medical.com");
        }
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

你可能感兴趣的:(springboot解决跨域问题)