I. Why cross-domain problems occur
Due to browser same-origin policy restrictions. Sameoriginpolicy is a convention that is the core and most basic security feature of browsers. Without Sameoriginpolicy, the normal functions of browsers may be affected. The Web is built on the same origin policy, and the browser is just an implementation of the same origin policy.
The same origin policy prevents javascript scripts in one domain from interacting with the contents of another domain. Same-origin means that both pages have the same protocol, host, and port number
What is cross-domain
If the protocol, domain name, or port used to request a URL is different from the current page URL, it is cross-domain
Third, non-homologous restriction
[1] Cannot read the Cookie, LocalStorage and IndexedDB of non-same-origin web pages
[2] The DOM of non-homologous web pages cannot be contacted
[3] Cannot send AJAX requests to non-same source addresses
Four, Java backend CORS cross – domain request mode
For CORS cross-domain requests, the following methods are available:
-
Returns the new CorsFilter
-
Rewrite WebMvcConfigurer
-
Use the annotation @Crossorigin
-
Manually set the response header (HttpServletResponse)
-
Custom Web Filter cross-domain implementation
Note:
-
CorFilter/WebMvConfigurer / @Crossorigin requires SpringMVC 4.2 or later, corresponding to springBoot 1.3 or later
-
The preceding two methods belong to global CORS configuration, and the latter two belong to local CORS configuration. The local cross-domain rule overwrites the global cross-domain rule if used, so the @Crossorigin annotation allows for more fine-grained cross-domain resource control.
-
In fact, either way, the ultimate goal is to modify the response header, to the response header to add data required by the browser, and then achieve cross-domain
1. Return the 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() {` `//1. Add CORS configuration information CorsConfiguration config = new CorsConfiguration(); Config.addallowedorigin ("*"); Whether ` ` / / send the Cookie ` ` config. SetAllowCredentials (true); Config.addallowedmethod ("*"); Config.addallowedheader ("*"); Config.addexposedheader ("*"); ` ` / / 2. Add the mapping path ` ` UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource (); ` `corsConfigurationSource.registerCorsConfiguration("/**",config); //3. Return new CorsFilter(CorsFilter); ` ` `} ` `}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) ' ` / / release any original domain ` `. AllowedOrigins (" * ") ` `. AllowedMethods (new String [] {" GET ", "POST", "PUT", "DELETE"})` `.allowedHeaders("*")` `.exposedHeaders("*"); ` ` `} ` `}Copy the code
3. Use annotations (local cross-domain)
Use the @CrossorIGin: annotation 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() {` `return "hello world"; ` ` `} ` `}Copy the code
Use the @crossorigin annotation on the method:
'@requestMapping ("/hello")' '@crossorigin (origins = "*")' '// @crossorigin (value = "http://localhost:8081" `public String hello() {` `return "hello world"; ` ` `}Copy the code
4. Manually set the response header (local cross-domain)
An HttpServletResponse object is used to add a response header (access-control-allow-Origin) to authorize the original field, where the value of Origin 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 a user-defined filter to cross domains
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() {}` `}`Copy the code
Configure this filter in web.xml to take effect
` <! -- Cross-domain access 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 access END --> 'Copy the code