In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to solve cross-domain problems in SpringBoot". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to solve cross-domain problems in SpringBoot.
1. Error reports for cross-domain access
When any one of the protocols, domain names and ports of a request url is different from the current page url, it is cross-domain.
For security reasons, browsers prohibit Ajax from calling resources that reside outside the current origin. For example, if an ajax request is sent from a.com to b.com, the browser console will report a cross-domain access error.
As shown in the figure below, when an ajax request is sent to ttp://localhost:8080/chat21/cors/test2 from the http://localhost:63342/ site page, a red error message appears. The error contains the word Access-Controll-Allow-Origin. When you see this later, you will see that this is a cross-domain problem.
2. Homologous definition
Homology policy is an important security policy of browsers, which is used to restrict how one source document or its loaded script interacts with another source. It can isolate malicious documents and reduce the media being attacked.
If the protocol, hostname and port number of the two URL are the same, then the two URL are of the same origin, otherwise the access from different sources and different sources will cause cross-domain problems, and the above error will occur.
The following table shows an example of comparison with the source of URL http://store.company.com/dir/page.html:
URL result reason http://store.company.com/dir2/other.html homologous only different paths, different https://store.company.com/secure.html non-homologous protocols, different http://store.company.com:81/dir/etc.html non-homologous port numbers, different http://news.company.com/dir/other.html non-homologous host names
In other words, when an AXJX request is made to the https://store.company.com, http://store.company.com:81 and http://news.company.com addresses on the http://store.company.com/dir/page.html site, it will fail and a cross-domain error will be reported. This is the same origin policy of the browser, which can only access data of the same origin.
3. How to solve the cross-domain problem?
The cross-domain problem needs to be solved by using CORS, and the requester and back-end interfaces need to follow CORS rules to communicate, so the problem of cross-domain access can be solved.
CORS, whose full name is Cross-Origin Resource Sharing, or cross-domain resource sharing, is a system composed of a series of HTTP headers that determine whether browsers prevent front-end javascript code from getting responses to cross-domain requests. Why do I need CORS? This is because the browser has a homologous security policy, and when we request resources from another domain in the current domain, the browser will by default prevent the script from reading its response, so CORS has a chance to display its talents.
Cross-source resource sharing (CORS) is a W3C specification implemented by most browsers that gives you the flexibility to specify what cross-domain requests are authorized instead of using less secure and less powerful policies such as IFRAME or JSONP.
4. CORS principle
The principle of CORS: to put it simply, some configurations are added to the request or response headers, through which cross-domain problems can be easily solved.
To learn more about the principle of CORS, it is recommended to read the following two articles, and then continue to read down, otherwise, finally you know how SpringMVC is solved, but do not know the essence of the principle.
CORS Communications: http://itsoku.com/article/197
Browser Security Policy & CORS: http://itsoku.com/article/198
5. How to solve the cross-domain problem in SpringMVC?
SpringMVC provides a solution to cross-domain problems. You only need to do some simple configuration, and the interface basically does not need to be modified to solve cross-domain problems.
The principle of SpringMVC to solve the cross-domain problem is that SpringMVC follows the rules of CORS communication to solve the cross-domain problem and adds some information needed by CORS in the response header.
Three solutions are provided in SpringMVC to solve cross-domain problems. Let's take a look at them.
6. Solution 1: the @ CrossOrigin annotation is marked on the method or class
The org.springframework.web.bind.annotation.CrossOrigin annotation is marked on the interface method. The @ CrossOrigin annotation is marked on the test1 interface below. This interface supports cross-domain access. The @ CrossOrigin annotation contains more detailed configuration, so I won't go into details here.
You can also mark @ CrossOrigin annotation on the class, so all interfaces in this class will support cross-domain access.
You can also mark @ CrossOrigin annotations on both classes and methods. Finally, the cross-domain access on the method will take the merged configuration.
@ RestControllerpublic class CorsController {@ RequestMapping ("/ cors/test1") @ CrossOrigin public List test1 () {List result = Arrays.asList ("www.itsoku.com", "Spring Master Series", "SpringMVC Series", "MySQL Series", "High concurrency Series"); return result 7. Scheme 2: the way of global configuration
In addition to fine-grained, annotation-based configurations, you may also need to define some global CORS configurations, similar to using filters, but can be declared as Spring MVC and combined with fine-grained @ CrossOrigin configurations. By default, all origins and GET, HEAD and POST methods are allowed.
@ EnableWebMvc@Configurationpublic class MvcConfig implements WebMvcConfigurer {@ Override public void addCorsMappings (CorsRegistry registry) {/ / you can add a cross-domain configuration for each call to registry.addMappin. If you need multiple configurations, you can call registry.addMapping registry.addMapping ("/ *") .allowedOrigins ("*") / / release which original domains .allowedMethods ("PUT", "DELETE") "POST", "GET") / / which request methods are released. AllowedHeaders ("header1", "header2", "header3") / which original request header information is released. ExposedHeaders ("header1", "header2") / which header information is exposed. AllowCredentials (false) / whether to send Cookie .maxAge (3600) / / Add more mappings... Scheme 3: the way of interceptor CorsFilter// handles cross-domain Filter//1. Add CORS configuration information CorsConfiguration config = new CorsConfiguration (); / / release which original domain config.addAllowedOrigin ("*"); / / whether to send Cookieconfig.setAllowCredentials (false); / / release which request method config.addAllowedMethod ("*"); / / release which original request header information config.addAllowedHeader ("*"); / / expose which header information config.addExposedHeader ("*"); / / 2. Add the mapping path UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource (); corsConfigurationSource.registerCorsConfiguration ("/ * *", config); 9. Case code 9.1, case complete code
Git address: https://gitee.com/javacode2018/springmvc-series
9.2. Interface code: CorsController
There are two interfaces in CorsController. The first interface is marked with @ CrossOrigin annotation, which can solve the problem of cross-domain access, while the second method is not marked.
@ RestControllerpublic class CorsController {@ RequestMapping ("/ cors/test1") @ CrossOrigin public List test1 () {List result = Arrays.asList ("www.itsoku.com", "Spring Master Series", "SpringMVC Series", "MySQL Series", "High concurrency Series"); return result } @ RequestMapping ("/ cors/test2") public List test2 () {List result = Arrays.asList ("www.itsoku.com", "Spring Master Series", "SpringMVC Series", "MySQL Series", "High concurrency Series"); return result;} 9.3, static pages: cors.html
Two buttons are added to the static page cors.html. When the two buttons are clicked, the above two interfaces are accessed in a cross-domain way of ajax. The first button accesses the first interface, and the second button accesses the second interface. Then check the results in the browser console.
Cors $(function () {$("# cors-btn1") .click (function () {$.ajax ({url: "http://localhost:8080/chat21/cors/test1", success: function (data) {console.log (JSON.stringify (data) })) $("# cors-btn2") .click (function () {$.ajax ({url: "http://localhost:8080/chat21/cors/test2", success: function (data) {console.log (JSON.stringify (data));}})) });}) Cross-domain testing test1 Cross-domain testing test29.4, publishing chat21-cores modules to tomcat
9.5. Run static page cors.html
Select cors.html in idea, then right mouse button-> Run, you can run
The running effect is as follows (preferably in a chrome browser). Static pages can be run directly in idea. Note that the port here is 63342, while the port of tomcat above is 8080. Then press F12 in the browser to open the browser console, select the Console tab, and later you can see the effect of clicking the button to verify the cross-domain effect.
9.6. Click the first button to test the cross-domain normal request
Take a look at the following figure. In a normal cross-domain request, the response header is added. The header at the beginning of Access-Control is related to CORS. The browser determines whether cross-domain access is normal based on these response headers. Without these headers, the browser will refuse to read the response body and report an error.
9.7. Click the second button to test the cross-domain exception request
At this point, I believe you have a deeper understanding of "how to solve cross-domain problems in SpringBoot". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.