SoFunction
Updated on 2025-04-12

Spring MVC cross-domain problem and solution

Cross-domain issues

Different domains

As long as there is one difference between protocol, domain name, and port, it is called a different domain

for example

fromhttp://testDraw and pull the resources corresponding to the following url

URL Whether it crosses the domain
http://test Not cross-domain
http://test Compare cross-domain
https://test Compare cross-domain

Tips:

  • Different domain pairsprotocoldomain nameportThe inspection of the three is very strict, for examplehttp://localhost:8080/testGo and pullhttp://127.0.0.1:8080/test2yesCompare cross-domain, because the domain names are different, although they express the same meaning.

Same Origin Policy

The browser itself will organize scripts loaded from one domain to obtain resources for another domain

Tips:

  • For resources like css and js, same-origin policies will not be triggered

Solution

Cross-domain resource sharing, as it supports all types of HTTP requests

Tips:

  • Only solve the problem of cross-domain browsers. If it involves cross-domain apps, mini programs, and IoT devices, SpringMVC may not take effect.

The front-end can obtain cross-domain resources through JSONP, but only supports GET requests.

3. Local solutions

@CrossOrigin

Add to the method or class@CrossOriginThis annotation sets the request domain for cross-domain access allowed in the response header.*Represents all, and can also be released one by one through string arrays.

@CrossOrigin({"http://localhost:8081", "http://localhost:8082"})
@GetMapping("/request")
public Student rest1(HttpServletResponse response) {
  Student student = new Student();
  ("GET Xiaolong");
  (23);
  (new Date());
  return student;
}

Tips:

  • The maxAge attribute in the annotation indicates the maximum duration of the pre-flight request result cache, the unit is seconds, the default is 1800s, that is, 30 minutes.

4. Global solution

There are actually many solutions to the cross-domain problem of browsers, and the essence is to set the content in the response headerAccess-Control-Allow-OriginThe value of the value is actually the domain we allow access above. For this, we only need to configure the response header of the response, so we can set the response header through the filter, and configure the value of the Spring to help us write the filter.

Handwriting filter

We write a class to implementFilterInterface, becauseFilterIn the interface, the initialization and destruction methods are the default implementation, and we don’t need them here, so there is no rewriting.

public class CrossOriginFilter implements Filter {
  
  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    // Conversion response    HttpServletResponse response = (HttpServletResponse) servletResponse;
    // Set the response header and set the allow access to all    ("Access-Control-Allow-Origin", "*");
    // Release    (servletRequest, response);
  }
}

Tips:

  • After the filter is written, we can configure it into the project. It can be configured using Java classes. For the specific method, please refer to the previous configuration filter.

Configure Spring configuration files

In most cases, we don’t need to use the handwriting filter. Spring has done it for us, and the functions are more complete than ours. We can use it directly

<!--ConfigurationmvcCross-domain access-->
<mvc:cors>
  <!--
    The corresponding map is our requesturl,Configuration哪一条允许跨域访问
    allowed-origins  =>Allow access requests
    allowed-methods  =>How to allow access
    max-age          =>Pre-flight request cache time
    -->
  <mvc:mapping path="/rest/**" allowed-origins="*" allowed-methods="POST" max-age="1888"/>
</mvc:cors>

Tips:

  • In path, if written/rest/*If it means that the child requested by rest, it will not request the grandchildren, for example/rest/test/test2No request
  • If written/rest/**The following means all the requests of descendants below rest, for example/rest/test/test2It can be requested

Config

Using Java classes to configure is actually similar, andWebMvcConfigIn the interface, we have provided the corresponding methodaddCorsMappings, we just need to re-replace the method.

@Override
public void addCorsMappings(CorsRegistry registry) {
  /*
      * Add Mapping in the registry, the parameter value is the path in the corresponding configuration file
      * Then you can keep clicking on the corresponding configuration properties in the xml
      */
  ("/rest/**")
          .allowedOrigins("*")
          .allowedMethods("POST")
          .maxAge(1811);
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.