search
HomeJavajavaTutorialHow does springboot solve cross-domain problems?

The content of this article is about how springboot solves cross-domain problems? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is a cross-domain HTTP request?

For security reasons, modern browsers must comply with the same origin policy when using the XMLHttpRequest object to initiate HTTP requests, otherwise Cross-domain HTTP requests are prohibited by default. Cross-domain HTTP requests refer to resources in domain A requesting resources in domain B. For example, the js code deployed on Nginx on machine A requests the RESTful interface deployed on Tomcat on machine B through ajax. (Recommended: Java Video Tutorial)

Different IP (domain name) or different ports will cause cross-domain problems. In order to solve cross-domain problems, there have been solutions such as jsonp and proxy files. The application scenarios were limited and the maintenance costs were high. Until HTML5 brought the CORS protocol.

CORS is a W3C standard, the full name is "Cross-origin resource sharing" (Cross-origin resource sharing), which allows browsers to issue XMLHttpRequest requests to cross-origin servers, thereby overcoming the problem that AJAX can only be used from the same origin. limit. It adds a special Header [Access-Control-Allow-Origin] to the server to tell the client about cross-domain restrictions. If the browser supports CORS and determines that the Origin is passed, XMLHttpRequest will be allowed to initiate cross-domain requests.

CROS common header

Access-Control-Allow-Origin: http://somehost.com indicates that http://somehost.com is allowed to initiate cross-domain requests.
Access-Control-Max-Age:86400 means that there is no need to send pre-verification requests within 86400 seconds.
Access-Control-Allow-Methods: GET, POST, PUT, DELETE indicates methods that allow cross-domain requests.
Access-Control-Allow-Headers: content-type indicates that cross-domain requests are allowed to include content-type

2. CORS implements cross-domain access

Authorization method
Method 1: Return a new CorsFilter
Method 2: Override WebMvcConfigurer
Method 3: Use annotation (@CrossOrigin)
Method 4: Manually set the response header (HttpServletResponse)

Note: Methods 1 and 2 belong to the global CORS configuration, and methods 3 and 4 belong to the local CORS configuration. If local cross-domain is used, it will override the global cross-domain rules, so the @CrossOrigin annotation can be used for finer-grained cross-domain resource control.

1. Return the new CorsFilter (global cross-domain)

package com.hehe.yyweb.config;

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
          //放行哪些原始域
          config.addAllowedOrigin("*");
          //是否发送Cookie信息
          config.setAllowCredentials(true);
          //放行哪些原始域(请求方式)
          config.addAllowedMethod("*");
          //放行哪些原始域(头部信息)
          config.addAllowedHeader("*");
          //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
          config.addExposedHeader("*");

        //2.添加映射路径
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}

2. Override WebMvcConfigurer (global cross-domain)

Any configuration class, Return a new WebMvcConfigurer Bean and rewrite the cross-domain request processing interface it provides to add mapping paths and specific CORS configuration information.

package com.hehe.yyweb.config;

@Configuration
public class GlobalCorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            //重写父类提供的跨域请求处理的接口
            public void addCorsMappings(CorsRegistry registry) {
                //添加映射路径
                registry.addMapping("/**")
                        //放行哪些原始域
                        .allowedOrigins("*")
                        //是否发送Cookie信息
                        .allowCredentials(true)
                        //放行哪些原始域(请求方式)
                        .allowedMethods("GET","POST", "PUT", "DELETE")
                        //放行哪些原始域(头部信息)
                        .allowedHeaders("*")
                        //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
                        .exposedHeaders("Header1", "Header2");
            }
        };
    }
}

3. Use annotations (local cross-domain)

Use the annotation @CrossOrigin on the method (@RequestMapping):

@RequestMapping("/hello")
@ResponseBody
@CrossOrigin("http://localhost:8080") 
public String index( ){
    return "Hello World";
}

or on the controller (@Controller) Use the annotation @CrossOrigin:

@Controller
@CrossOrigin(origins = "http://xx-domain.com", maxAge = 3600)
public class AccountController {

    @RequestMapping("/hello")
    @ResponseBody
    public String index( ){
        return "Hello World";
    }
}
  1. Manually set the response header (partial cross-domain)

Use the HttpServletResponse object to add the response header (Access-Control-Allow-Origin) for authorization Original domain, the value of Origin here can also be set to "*", which means all are allowed.

@RequestMapping("/hello")
@ResponseBody
public String index(HttpServletResponse response){
    response.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
    return "Hello World";
}

3. Test cross-domain access

First use Spring Initializr to quickly build a Maven project without changing anything. In the static directory, add a page: index.html to simulate cross-domain access. Target address: http://localhost:8090/hello

nbsp;html>


    <meta>
    <title>Page Index</title>


<h2 id="前台系统">前台系统</h2>
<p></p>

<script></script>
<script>
    $.ajax({
        url: &#39;http://localhost:8090/hello&#39;,
        type: "POST",
        xhrFields: {
           withCredentials: true //允许跨域认证
        },
        success: function (data) {
            $("#info").html("跨域访问成功:"+data);
        },
        error: function (data) {
            $("#info").html("跨域失败!!");
        }
    })
</script>

Then create another project, add the Config directory in the Root Package and create a configuration class to enable global CORS.

package com.hehe.yyweb.config;

@Configuration
public class GlobalCorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

Next, simply write a Rest interface and specify the application port as 8090.

package com.hehe.yyweb;

@SpringBootApplication
@RestController
public class YyWebApplication {

    @Bean
    public TomcatServletWebServerFactory tomcat() {
        TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory();
        tomcatFactory.setPort(8090); //默认启动8090端口
        return tomcatFactory;
    }

    @RequestMapping("/hello")
    public String index() {
        return "Hello World";
    }

    public static void main(String[] args) {
        SpringApplication.run(YyWebApplication.class, args);
    }
}

Finally, start the two applications respectively, and then access: http://localhost:8080/index.html in the browser. JSON data can be received normally, indicating that the cross-domain access is successful! !


The above is the detailed content of How does springboot solve cross-domain problems?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)