“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”

First, why do cross-domain problems occur

The same origin policy is restricted by the browser. The Sameoriginpolicy is a convention. It is the core and basic security function of the browser. If the Sameoriginpolicy is missing, the normal functions of the browser may be affected. The Web is built on the same origin policy, and browsers are just an implementation of the same origin policy. The same origin policy prevents javascript scripts in one domain from interacting with content in another domain. Same-origin (that is, in the same domain) means that two pages have the same protocol, host, and port.

What is cross-domain

When the protocol, domain name, or port of a URL request is different from the current page URL, it is called cross-domain

3. Non-homologous restriction

[1] Cookies, LocalStorage and IndexedDB of non-same-origin web pages cannot be read

[2] DOM of non-homologous web pages cannot be accessed

[3] Unable to send AJAX requests to non-homologous addresses

Fourth, Java backend implementation of CORS cross-domain request

For cross-domain requests of CORS, there are mainly the following options:

  1. Returns a new CorsFilter
  2. Rewrite WebMvcConfigurer
  3. Use the annotation @crossorigin
  4. Manually set the response header (HttpServletResponse)
  5. Custom Web Filters are implemented across domains

= = note: = =

  • CorFilter/WebMvConfigurer / @Crossorigin requires SpringMVC 4.2 or later, which corresponds to springBoot 1.3 or later
  • The first two methods belong to global CORS configurations, while the last two methods belong to local CORS configurations. Local cross-domain rules override global cross-domain rules if used, so you can use @crossorigin annotations for more fine-grained cross-domain resource control.
  • == In either case, the goal is to modify the response header by adding the data required by the browser to the response header to achieve cross-domain ==.

1. Return new CorsFilter(global cross-domain)

In any configuration class, return a new CorsFIlter Bean and add the mapping path and the specific CORS configuration path.

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter(a) {
        //1. Add CORS configuration information
        CorsConfiguration config = new CorsConfiguration();
        // Which primitive fields are allowed
        config.addAllowedOrigin("*");
        // Whether to send cookies
        config.setAllowCredentials(true);
        // Which requests are allowed
        config.addAllowedMethod("*");
        // Which original request headers are allowed
        config.addAllowedHeader("*");
        // What header information is exposed
        config.addExposedHeader("*");
        //2. Add a mapping path
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/ * *",config);
        //3. Return a new CorsFilter
        return newCorsFilter(corsConfigurationSource); }}Copy the code

2. Rewrite WebMvcConfigurer(global Cross-domain)

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/ * *")
                // Whether to send cookies
                .allowCredentials(true)
                // Which primitive fields are allowed
                .allowedOrigins("*")
                .allowedMethods(new String[]{"GET"."POST"."PUT"."DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*"); }}Copy the code

3. Use annotations (local cross-domain)

Use the annotation @crossorigin: on the controller (on the class) to indicate that all methods of the class are allowed to cross domains.

@RestController
@CrossOrigin(origins = "*")
public class HelloController {
    @RequestMapping("/hello")
    public String hello(a) {
        return "hello world"; }}Copy the code

Use annotations on methods @crossorigin:

@RequestMapping("/hello")
    @CrossOrigin(origins = "*")
     // @crossorigin (value = "http://localhost:8081") // Specify a specific IP address that can cross domains
    public String hello(a) {
        return "hello world";
    }
Copy the code

4. Manually set response headers (local cross-domain)

The HttpServletResponse object is used to add a response header (Access-Control-allow-Origin) to authorize the original field, where the Origin value can also be set to “*” to permit all.

    @RequestMapping("/index")
    public String index(HttpServletResponse response) {
        response.addHeader("Access-Allow-Control-Origin"."*");
        return "index";
    }
Copy the code

5. Use custom filters to achieve cross-domain implementation

Start by writing a filter, which you can call mycorsfilter.java

package com.mesnac.aop;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
@Component
public class MyCorsFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin"."*");
    response.setHeader("Access-Control-Allow-Methods"."POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age"."3600");
    response.setHeader("Access-Control-Allow-Headers"."x-requested-with,content-type");
    chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy(a) {}}Copy the code

2. Configure the filter in web.xml to take effect

<! START--> <filter> <filter-name>CorsFilter</filter-name> <filter-class>com.mesnac.aop.MyCorsFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>CorsFilter</filter-name>
	<url-pattern/ * < / >url-pattern>
</filter-mapping> <! -- Cross-domain accessEND  -->

Copy the code

5. Reference connection

  1. Implementing Cross-domain Requests (CORS) in springBoot series
  2. The Java Web uses filters to enable cross-domain access to sites
  3. Spring Boot2: CORS solving cross-domain problems