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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • ubuntu 通过命令行 卸载软件_命令提示符卸载软件

    ubuntu 通过命令行 卸载软件_命令提示符卸载软件1、在终端里apt-get安装的软件:安装软件sudo apt-getinstallsoftname1softname2softname3……卸载软件sudoapt-getremovesoftname1softname2softname3……卸载并清除配置sudo apt-getremove–purgesoftname1更新软件信息数据库sudoapt-getu…

    2025年10月13日
    2
  • win10双系统重装ubuntu_双系统win10无法启动

    win10双系统重装ubuntu_双系统win10无法启动&amp;amp;amp;amp;NBSP;&amp;amp;amp;amp;NBSP;&amp;amp;amp;amp;NBSP;&amp;amp;amp;amp;NBSP;这两天笔者安装win10+ubuntu16.04双系统,因为网络上能找到大量的资料,安装过程此处就不多讲。因为笔者电脑是华硕主板,bios默认设置为安全启动,笔者猜测会阻止加载ubuntu引导,导致双系统不能随意引导。先不管那么多,现在的问题是Ubuntu已经安装成功,开机直接进入win10,所以笔者的

    2022年10月21日
    3
  • ubuntu安装中文输入法搜狗_中文输入法怎么调出来

    ubuntu安装中文输入法搜狗_中文输入法怎么调出来请注意命令中不应该的空格可能导致命令不合法!一、检查fctix框架首先,要安装中文输入法,必须要保证系统上有fctix。fctix是一个以GPL方式发布的输入法框架,安装fctix后可以为操作系统的桌面环境提供一个灵活的输入方案,解决在GNU/Linux环境下安装中文输入法的问题。win+a打开所有应用程序,找到Language…

    2022年9月26日
    4
  • android gridview控件使用详解_android tablelayout

    android gridview控件使用详解_android tablelayoutfrom:http://blog.csdn.net/weich_java/article/details/6987198笔者在用GridView时发现GridView的selectstyle会根据系统而不同,因为在客户端中一边具有统一的显示风格,所以尝试了下指定GridView的选中样式。首先看一下代码:menu.xmlandroid:layout_width=”fill_parent”andr…

    2022年9月25日
    1
  • Matlab绘图方法整理(超完整版)[通俗易懂]

    Matlab绘图方法整理(超完整版)[通俗易懂]超详细版Matlab绘图方法整理,1万字文章让你流畅掌握Matlab作图方法,保证你能完全掌握常用作图手段,谁又不想做一幅详细、美丽的图呢?

    2022年6月30日
    26
  • phpstorm最新激活码linux版_最新在线免费激活2022.03.11

    (phpstorm最新激活码linux版)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~1M2OME2TZY-eyJsaWNlb…

    2022年3月13日
    246

发表回复

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

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