Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the Cross-Domain problem of Cors in all aspects by Springboot2.X

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to solve the cross-domain problem of Cors in all aspects of Springboot2.X, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

I. Conceptual understanding Cors

1.1. what is Cors?

Directly interpreted as cross-domain, it is a better existence than jsonp. JSONP only supports Get requests, and CORS supports all types of HTTP requests.

1.2. What is cross-domain?

Homology means that the domain name, protocol and port are all the same, and if they are different, they are all counted as cross-domain. The ajax interface of website A to website B is cross-domain, as explained below.

Non-cross-domain: http://www.osc.com/index.html calls http://www.osc.com/index.php non-cross-domain: http://www.osc.com/index.html calls http://www.qq.com/index.php cross-domain, different main domain http://abc.osc.com/index.html calls http://def.osc.com/server.php cross-domain Sub-domain different http://www.osc.com:8080/index.html call http://www.osc.com/server.php cross-domain, different port https://www.osc.com/index.html call http://www.osc.com/server.php cross-domain, different protocols (difference between https and http) 2. Prepare Project A

Prepare 2 Springboot projects, different port numbers, A project ajax access B project interface, which can be regarded as cross-domain access. I will put all the code used on it, saving everyone from commenting on why I can't do this.

Project A: springboot+freemaker

2.1 、 pom.xml

Org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web

2.2 、 application.properties

Server.port=8089server.servlet.context-path=/tssd#thymeleafspring.mvc.view.prefix=classpath:/templates/spring.mvc.view.suffix=.htmlspring.thymeleaf.cache=falsespring.mvc.static-path-pattern=/**spring.resources.static-locations = classpath:/static/spring.thymeleaf.mode=LEGACYHTML5

2.3 、 controller

@ Controllerpublic class EveryController {@ RequestMapping (value = "/ every/ {url}") public String toEveryUrl (@ PathVariable ("url") String url) {return url;}}

2.4.The index.html under the templates folder. Now this ajax accesses 8082, so the port number of project B must be 8082.

Xixi i love you,my beast love girl aoxin $(function () {$.ajax ({url: "http://localhost:8082/test", type:" POST ", dataType:" json ", success: function (data) {alert (data.data)) }, error: function () {alert (error);});})

After a while, we go directly to index.html through the interface http://localhost:8089/tssd/every/index, and then the page load function ajax requests the B project interface.

III. B project creation

3.1 、 pom.xml

Org.springframework.boot spring-boot-starter-web

3.2 、 application.properties

Server.port=8082

3.3, entity class

@ Data@AllArgsConstructorpublic class Result {private boolean success; private String code; private String message; private Object data; public Result () {this.success = true; this.code = "200";}}

Then the rest doesn't need to be configured, and that's it, Project B ends.

Method 1: method local solution to cross-domain

It is to solve the spanning problem for a certain interface.

In Project B, use annotations on the method so that our method can be cross-domain.

@ CrossOrigin (origins = "http://localhost:8089",maxAge = 3600) @ RequestMapping (value =" / test ", method = RequestMethod.POST) @ ResponseBodypublic Result testOne () {Result result = new Result (); result.setData (" fjsd "); return result;}

Http://localhost:8089/tssd/every/index

Method 2: local solution to cross-domain and so on.

Apply method one's annotation CrossOrigin on a method to a class so that all methods of that class can be cross-domain.

Controller@CrossOrigin (origins = "http://localhost:8089",maxAge = 3600) public class FirstController {@ RequestMapping (value =" / test ", method = RequestMethod.POST) @ ResponseBody public Result testOne () {Result result = new Result (); result.setData (" fjsd "); return result;}}

The successful screenshot is the same as above, but the implementation is not the same. Of course, if your comments are only written as

@ CrossOrigin (maxAge = 3600)

Then it can be accessed by any website. It has been tested. You can remove origins and origins.

Method 3: global configuration to solve cross-domain

Remove the annotations of method 1 and method 2, add global configuration, configure interface paths that can cross domains, and so on.

@ Configurationpublic class MyCrosConfig implements WebMvcConfigurer {@ Override public void addCorsMappings (CorsRegistry registry) {registry.addMapping ("/ test") .allowedOrigins ("http://localhost:8089") .allowedM ethods (" PUT "," DELETE "," POST "," GET ") .allowedHeaders (" * ") .maxAge (3600); method IV: filter to solve cross-domain

You can remove the annotations or @ Configuration from the previous three methods, and then we'll test them with the fourth method.

@ Configurationpublic class CrosFilter {@ Bean CorsFilter getCorsFilter () {CorsConfiguration cors = new CorsConfiguration (); cors.setAllowCredentials (true); cors.addAllowedMethod ("*"); cors.addAllowedOrigin ("*"); cors.setMaxAge (3600L); cors.addAllowedHeader ("*"); cors.applyPermitDefaultValues (); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource (); source.registerCorsConfiguration ("/ *", cors) CorsFilter corsFilter = new CorsFilter (source); return corsFilter;}}

Result: success.

VIII. Summary

In fact, there are not only local methods, local classes, global configuration and filter methods, but also xml methods, but I don't like it, so I won't introduce it to you. After all, Springboot does not advocate using xml, so you can follow me if you like, hee hee.

This is the end of the answer on how to solve the cross-domain problem of Cors by Springboot2.X. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report