Spring MVC -- 12 cross domain issues

Posted by zulfer on Sat, 22 Jan 2022 08:20:49 +0100

15 cross domain issues

15.1 different domains

As long as there is one difference among protocol, domain name and port, they are called different domains

  • For example:

    From http: / moon COM / test to pull the resources corresponding to the following url

    URLCross domain
    http:/moon.com/testNot cross domain
    http:/www.moon.com/testComputational cross domain
    https:/moon.com/testComputational cross domain
  • Tips:

    Different domains check the protocol, domain name and port very strictly, for example, from http://localhost:8080/test Go pull http://127.0.0.1:8080/test2 It is cross domain because the domain names are different, although they express the same meaning.

15.2 homology strategy

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

Tips:

  • For resources such as css and js, the same origin policy will not be triggered

15.3 solutions

15.3.1 CORS

Cross domain resource sharing because it supports all types of HTTP requests

Tips:

  • It can only solve the cross domain problem of browsers. If apps, applets and Internet of things devices are involved, spring MVC may not take effect

15.3.2 JSONP

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

15.3.3 local solutions

@CrossOrigin

Add the @ CrossOrigin annotation to the method or class to set the cross domain access request field allowed in the response header, * represents all, and can also be released one by one in the form of string array

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

Tips:

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

15.3.4 Global Solutions

In fact, there are many solutions to the cross domain problem of the browser. Its essence is to set the value of access control allow origin in the response header. Its value is actually the domain we are allowed to 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 filter written by Spring

15.3.4.1 handwriting filter

We write a class to implement the Filter interface. Because the initialization and destruction methods in the Filter interface are implemented by default, we don't need them here, so we don't rewrite them.

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

Tips:

  • After the filter is written, we can configure it into the project and use web XML or java class configuration. Please refer to the previous configuration filter for details
15.3.4.2 configuring Spring configuration files

In most cases, we don't need to use the handwriting filter. Spring has done it for us, and the function is more perfect than ours. We can take it directly

<!--to configure mvc Cross domain access-->
<mvc:cors>
  <!--
    The mapping corresponds to our request url,Configure which allows cross domain access
    allowed-origins  =>Request to allow access
    allowed-methods  =>Ways to allow access
    max-age          =>Pre check request cache time
    -->
  <mvc:mapping path="/rest/**" allowed-origins="*" allowed-methods="POST" max-age="1888"/>
</mvc:cors>

Tips:

  • In path, if it is written as / rest / *, it means that the child requests under rest will not be requested to the grandchildren. For example, / rest/test/test2 cannot be requested
  • If it is written as / rest / * * it means that all descendant requests under rest, such as / rest/test/test2, can be requested
15.3.4.3 configuring JavaConfig

Using Java classes for configuration is basically the same, and the corresponding method addCorsMappings has been provided for us in the WebMvcConfig interface. We only need to re configure this 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 go all the way to configure the attributes in the corresponding xml
     */
  registry.addMapping("/rest/**")
          .allowedOrigins("*")
          .allowedMethods("POST")
          .maxAge(1811);
}

Topics: Java Spring Spring MVC