SoFunction
Updated on 2025-03-08

Several examples of solutions to cross-domain problems in Java are explained in detail

Preface

In front-end separation projects, cross-domain problems are often encountered. The article introduces the example code in detail. Friends who need it can refer to it and take a look~

What is cross-domain

When the protocol, domain name, or port of a requested url is different from the url of the current page, it is a cross-domain.

For example, if page a wants to obtain the resources of page b, the protocol, domain name or port number of page b is different, and the access behaviors performed are cross-domain. Due to the same-origin policy of the browser, cross-domain request resources will be restricted.

The same-origin policy was introduced into the browser by Netscape. Currently, all browsers implement this policy. Initially, its meaning was that the cookies set by A and B pages cannot be opened unless the two pages are "homologous". The so-called "homologous" refers to "three identical":

  • The same agreement
  • The domain name is the same
  • Same port

The same-origin policy ensures that resources in an application can only be accessed by resources of this application.

Non-homologous restriction

  • Cookies, localStorage, indexDB cannot be read
  • DOM and js objects cannot be obtained
  • Unable to send Ajax request

Cross-domain problems in Java refer to the fact that when using Ajax technology for cross-domain access, the request is denied or the correct response result cannot be obtained due to browser security restrictions.

To solve cross-domain problems in Java, you can use the following methods:

1. Support cross-domain access by setting response header information.

In Java, you can support cross-domain access by setting response headers, for example, in Spring MVC

//@CrossOrigin annotation to set the source address that allows cross-domain access:@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping("/api")
@RestController
public class ApiController {
    // ...
}

2. Use iframe to achieve cross-domain access.

Cross-domain access can be achieved by using the iframe element in the same page, thus avoiding browser security restrictions. For example, in the front-end page, data from different domain names can be obtained in the following ways:

var iframe = ('iframe');
 = '/data';
 = 'none';
(iframe);
var data = ;
(data);

Or the front-end sends ajax request

    $("#test").click(function(){
        $.ajax({
            url : "http://localhost:8082/",
            type : "GET",
            success : function(result){
                // alert(result);
                (result)
            }
        })
    })

3. Use WebSocket to solve cross-domain problems.

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        (new MyWebSocketHandler(), "/data").setAllowedOrigins("*");
    }
}

4. HttpServletResponse add header information

@RestController
public class CorsController {
​
    @RequestMapping(value = "/")
    public String hello(HttpServletResponse response){
        ("Access-Control-Allow-Origin","http://localhost:8081");
        //("Access-Control-Allow-Credentials","true");
        return "hello cors";
    }
    
}

5. Solve cross-domain through configuration classes

Using HttpServletResponse object or annotation method, you need to add corresponding annotations or parameters to each method that needs to cross-domain. We want all controllers to add cross-domain functions, which we can implement byWebMvcConfigurerInterface customizes cross-domain configuration.

WebMvcConfigurer is an interface that provides many custom interceptors, such as cross-domain settings, type converters and other springMVC configurations.

@Configuration
public class CorsConfig implements WebMvcConfigurer {
​
    /**
      **addMapping**: The configuration can be cross-domain paths, can be configured arbitrarily, and can be specifically used to directly request paths.
      *
      * **allowedMethods**: Allows all request methods to access the cross-domain resource server, such as: POST, GET, PUT, DELETE, etc.
      *
      **allowedOrigins**: All requested domain names allow access to our cross-domain resources. You can fix a single or multiple content, such as: "[](/)". Only this domain name can access our cross-domain resources.
      *
      **allowedHeaders**: All request headers are allowed to access, and any request header information can be customized.
     
      * @param registry
      */
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        ("/*.cors")
                .allowedOrigins("http://localhost:8081")
                .allowedMethods("POST","GET")
                .maxAge(1000);
    }
}

Summarize

This is the end of this article about several ways to solve cross-domain problems in Java. For more related content on cross-domain problems in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!