java后端解决跨域问题[通俗易懂]

java后端解决跨域问题[通俗易懂]java后端解决跨域问题

大家好,又见面了,我是你们的朋友全栈君。

1.java过滤器过滤

允许整个项目跨域访问,可通过filter来进行过虑:

public class SimpleCORSFilter implements Filter{ 
     
  
    @Override  
    public void destroy() { 
     
          
    }  
  
    @Override  
    public void doFilter(ServletRequest req, ServletResponse res,  
            FilterChain chain) throws IOException, ServletException { 
     
            HttpServletResponse response = (HttpServletResponse) res;  
            response.setHeader("Access-Control-Allow-Origin", "*");  
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");  
            response.setHeader("Access-Control-Max-Age", "3600");  
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");  
            chain.doFilter(req, res);  
          
    }  
  
    @Override  
    public void init(FilterConfig arg0) throws ServletException { 
     
          
    }  
  
}

在web.xml中需要添加如下配置:

<filter>  
      <filter-name>cors</filter-name>  
      <filter-class>com.ssm.web.filter.SimpleCORSFilter</filter-class>  
    </filter>  
    <filter-mapping>  
      <filter-name>cors</filter-name>  
      <url-pattern>/*</url-pattern> </filter-mapping> </filter> 

为单个方法提供跨域访问,直接添加请求头:

       response.setHeader("Access-Control-Allow-Origin", "*");  
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");  
            response.setHeader("Access-Control-Max-Age", "3600");  
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

2.后台Http请求转发

使用HttpClinet转发进行转发(简单的例子 不推荐使用这种方式)

try {
    HttpClient client = HttpClients.createDefault();            //client对象
    HttpGet get = new HttpGet("http://localhost:8080/test");    //创建get请求
    CloseableHttpResponse response = httpClient.execute(get);   //执行get请求
    String mes = EntityUtils.toString(response.getEntity());    //将返回体的信息转换为字符串
    System.out.println(mes);
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

3、后台配置同源Cors (推荐)

在SpringBoot2.0 上的跨域 用以下代码配置 即可完美解决你的前后端跨域请求问题

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;
/**
 * 实现基本的跨域请求
 * @author linhongcun
 *
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*是否允许请求带有验证信息*/
        corsConfiguration.setAllowCredentials(true);
        /*允许访问的客户端域名*/
        corsConfiguration.addAllowedOrigin("*");
        /*允许服务端访问的客户端请求头*/
        corsConfiguration.addAllowedHeader("*");
        /*允许访问的方法名,GET POST等*/
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

4、使用SpringCloud网关

服务网关(zuul)又称路由中心,用来统一访问所有api接口,维护服务。
Spring Cloud Zuul通过与Spring Cloud Eureka的整合,实现了对服务实例的自动化维护,所以在使用服务路由配置的时候,我们不需要向传统路由配置方式那样去指定具体的服务实例地址,只需要通过Ant模式配置文件参数即可

5、使用nginx做转发

现在有两个网站想互相访问接口 在http://a.a.com:81/A中想访问 http://b.b.com:81/B 那么进行如下配置即可
然后通过访问 www.my.com/A 里面即可访问 www.my.com/B

s

erver {
        listen       80;
        server_name  www.my.com;
        location /A {
            proxy_pass  http://a.a.com:81/A;
            index  index.html index.htm;
        }
        location /B {
            proxy_pass  http://b.b.com:81/B;
            index  index.html index.htm;
        }
    }

如果是两个端口想互相访问接口 在http://b.b.com:80/Api中想访问 http://b.b.com:81/Api 那么进行如下配置即可
使用nginx转发机制就可以完成跨域问题

server {
        listen       80;
        server_name  b.b.com;
        location /Api {
            proxy_pass  http://b.b.com:81/Api;
            index  index.html index.htm;
        }
    }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/106614.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Boltzmann机详解

    Boltzmann机详解基于热力学的随机型神经网络–Boltzmann机1.模拟退火算法我们知道,Hopfield神经网络拥有联想记忆的能力,这也是对生物神经网络的一种模拟。但是,Hopfield神经网络也和BP神经网络一样,有一个致命的缺陷:只能找到局部最优解,而无法沿着梯度上升的方向在全局的角度寻求全局最优解。为了解决这个问题,1983年,Kirkpatrick等提出了模拟退火算法(SA)能有效的解决局部最优…

    2022年7月12日
  • NPM设置淘宝镜像命令

    npmconfigsetregistryhttp://registry.npm.taobao.org/转载于:https://my.oschina.net/hlhgo/blog/…

    2022年4月10日
  • Linux命令速查手册出炉!

    点击上方“全栈程序员社区”,星标公众号 重磅干货,第一时间送达 来源:MarkerHub 查看Linux系统信息 arch    &nbsp…

    2021年6月26日
  • LOAM, ALOAM, LegoLOAM, hdl graph slam比较

    LOAM, ALOAM, LegoLOAM, hdl graph slam比较A-LOAMLOAM:•LOAMuseanewdefinedfeaturesystem(cornerandflatpoint),forthedetailseeitsarticle.•LOAMsupposelinearmotionwithinthescanswap(VLOAMfurtherusesvisualodometrytoe…

    2022年10月31日
  • javascript获取当前时间,按指定格式输出_js获取现在本地时间的代码

    javascript获取当前时间,按指定格式输出_js获取现在本地时间的代码使用js获取当前时间

    2022年9月23日
  • Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)

    Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)本文会从传统的BIO到NIO再到AIO自浅至深介绍,并附上完整的代码讲解。1、BIO编程1.1、传统的BIO编程网络编程的基本模型是C/S模型,即两个进程间的通信。服务端提供IP和监听端口,客户端通过连接操作想服务端监听的地址发起连接请求,通过三次握手连接,如果连接成功建立,双方就可以通过套接字进行通信。传统的同步阻塞模型开发中,ServerSocket负责绑定IP地址,启动监听端口;Socket负责发起连接操作。连接成功后,双方通过输入和输出流进行同步阻塞式通信。

    2022年6月14日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号