What are the ways springboot solves CORS cross-domain issues?
1. Implement the WebMvcConfigurer interface
@Configuration public class WebConfig implements WebMvcConfigurer { /** * 添加跨域支持 */ @Override public void addCorsMappings(CorsRegistry registry) { // 允许跨域访问的路径 '/**'表示应用的所有方法 registry.addMapping("/**") // 允许跨域访问的来源 '*'表示所有域名来源 .allowedOriginPatterns("*") // .allowedOrigins("*") // 允许跨域访问的来源 SpringBoot2.4.0之前的版本 // 允许跨域请求的方法 '*'表示所有 .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") // 是否允许发送cookie true-允许 false-不允许 默认false。对服务器有特殊要求的请求,比如请求方法是PUT或DELETE,或者Content-Type字段的类型是application/json,这个值只能设为true .allowCredentials(true) // 预检间隔时间1小时,单位为秒。指定本次预检请求的有效期,在有效期间,不用发出另一条预检请求。 // 浏览器发出CORS简单请求,只需要在头信息之中增加一个Origin字段 // 浏览器发出CORS非简单请求,会在正式通信之前,增加一次OPTIONS查询请求,称为"预检"请求(preflight)。浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些HTTP动词和头信息字段。只有得到肯定答复,浏览器才会发出正式的XMLHttpRequest请求,否则就报错。 .maxAge(3600) // 允许跨域请求可携带的header,'*'表所有header头。CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定 .allowedHeaders("*"); } }
2. Implement the filter filter method
@WebFilter @Configuration public class CorsFilter implements Filter { @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-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); chain.doFilter(req, res); } }
3. The annotation @CrossOrigin
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
@CrossOrigin can be configured on the method, and also Configurable on classes.
4. Practical combat
Create two ordinary SpringBoot projects A and B. A is configured with port 8081, and port B is configured with port 8082.
Create an html file index.html in A's resources/static directory:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <!-- jquery库可百度jquery cdn --> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script> <script> function btnClick() { $.get('http://localhost:8082/hello/hello', function (msg) { $("#app").html(msg); }); } function btnClick2() { $.post('http://localhost:8082/hello/hello', function (msg) { $("#app").html(msg); }); } </script> <body> <div id="app"></div> <input type="button" onclick="btnClick()" value="get_button"> <input type="button" onclick="btnClick2()" value="post_button"> </body> </html>
B provides 2 web interfaces:
@RestController @RequestMapping("/hello") public class HelloController { // @CrossOrigin(originPatterns = "*", allowCredentials = "true") @GetMapping("/hello") public String hello() { System.out.println("get hello"); return "get hello"; } // @CrossOrigin(originPatterns = "*", allowCredentials = "true") @PostMapping("/hello") public String hello2() { System.out.println("post hello"); return "post hello"; } }
Start A and B services respectively, The browser accesses A's index.html and clicks the button. The browser console reports the following error: http://localhost:8081/index.html
Access to XMLHttpRequest at ' http://localhost:8082/hello/hello' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Use method 1 for project B, add cross-domain support, restart, click the button again, you can access normally, observe that the response header has more cross-domain support information:
SpringBoot 2.6 and above
The available configuration can be found online (but the personal test is invalid!):server.servlet.session.cookie.same-site=none server.servlet.session.cookie.secure=true
SpringBoot 2.6 or below Version
If you use Tomcat as the server, you can set the SameSite attribute of the session cookie through the following configuration (personal test does not work!).server.servlet.session.cookie.secure=true
@Configuration public class TomcatCookieConfig { @Bean public TomcatContextCustomizer sameSiteCookiesConfig() { return context -> { final Rfc6265CookieProcessor cookieProcessor = new Rfc6265CookieProcessor(); // SameSite cookieProcessor.setSameSiteCookies(SameSiteCookies.NONE.getValue()); context.setCookieProcessor(cookieProcessor); }; } }
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-core</artifactId> </dependency>
@Configuration public class SpringSessionConfiguration { @Bean public CookieSerializer cookieSerializer() { DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer(); // Strict-严格模式 Lax-松懈模式 None-无 cookieSerializer.setSameSite("None"); cookieSerializer.setUseSecureCookie(true); return cookieSerializer; } }
@Configuration public class CookieConfig { private static String domain; @Value("${domain}") public void setDomain(String domain) { CookieConfig.domain = domain; } public static HttpCookie generateHttpCookie(String name, String value) { return ResponseCookie.from(name, value) .domain(domain) // cookie跨域设置 .sameSite("None") // 在https下传输,配合sameSite=None使用 .secure(true) .path("/") // 有效期24小时 .maxAge(60 * 60 * 24) .build(); } }
@GetMapping("/hello") public String hello(HttpServletResponse response) { HttpCookie cookie2 = CookieConfig.generateHttpCookie("age", "18"); response.addHeader(HttpHeaders.SET_COOKIE, cookie2.toString()); HttpCookie cookie3 = CookieConfig.generateHttpCookie("id", "77"); response.addHeader(HttpHeaders.SET_COOKIE, cookie3.toString()); System.out.println("get hello"); return "get hello"; }
The above is the detailed content of What are the ways springboot solves CORS cross-domain issues?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic
