Table of Contents
3. Use annotations (local cross-domain)
Home Java javaTutorial How does springboot solve cross-domain problems?

How does springboot solve cross-domain problems?

Mar 19, 2019 am 10:17 AM
java spring

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);
    }
}
Copy after login

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");
            }
        };
    }
}
Copy after login

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";
}
Copy after login

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";
    }
}
Copy after login
  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";
}
Copy after login

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Page Index</title>
</head>
<body>
<h2>前台系统</h2>
<p id="info"></p>
</body>
<script src="webjars/jquery/3.2.1/jquery.js"></script>
<script>
    $.ajax({
        url: 'http://localhost:8090/hello',
        type: "POST",
        xhrFields: {
           withCredentials: true //允许跨域认证
        },
        success: function (data) {
            $("#info").html("跨域访问成功:"+data);
        },
        error: function (data) {
            $("#info").html("跨域失败!!");
        }
    })
</script>
</html>
Copy after login

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("/**");
            }
        };
    }
}
Copy after login

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);
    }
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles