Spring boot series learn spring boot's multiple cross domain solutions in minutes

Spring boot series (8) minutes learn a variety of cross domain solutions of spring boot

Previous recommendation
Spring boot series (I) idea new spring boot project

Introduction to SpringBoot series (2)

Spring boot series (3) configuration file details

Spring boot series (IV) detailed explanation of web static resource configuration

Spring boot series (V) Mybatis integrated full detailed version

Spring boot series (6) integrated tymeleaf detailed Edition

Springboot series (seven) integration interface document swagger, use, test

**Table of contents**

1. How to understand cross domain

What is cross domain?

  cross domain refers to the mutual access between different domain names, which is determined by the browser's homology policy. It is the security measures imposed by the browser on JavaScript to prevent malicious file damage.

Homology policy: homology policy is a kind of convention, which is the core and basic security policy of browser. If homology policy is missing, the normal function of browser may be affected.
The so-called homology means that the protocol, domain name and port number are completely consistent, and one inconsistency will cause cross domain problems.

Cross domain principle:

  • The cross domain request can be sent out normally, and the server can receive the request and return the result normally, but the result is blocked.
  • Cross domain only exists in browsers, not in other platforms, such as Android / java/ios.
  • The reason why cross domain occurs is due to the restriction of the same source policy, which requires the same source to communicate normally, that is, the protocol, domain name and port number are all identical.

URL: uniform resource locator, which is the uniform resource locator of www, that is to say, the network address. Its general format is: protocol type: / / server address: port number / path.
This is what we call a cross domain domain.

2. Three cross domain solutions in sprint boot

Cross domain technology CORS:

CORS is a W3C standard, full name is "cross origin resource sharing". It allows browsers to issue XMLHttpRequest requests to cross source servers, thus overcoming the limitation that AJAX can only be used from the same source.

  SpringBoot supports Cross very well. There are currently three Cross domain approaches.

1. CrossOrigin notes

//@CrossOrigin means that all URL s can access this resource
@CrossOrigin(origins = " ") / / indicates that only one url is allowed to access the controller across domains
public class CorssOriginController {

    //This note can be applied to the method
    //@CrossOrigin(origins = "")
    public String getString(){
        return "Cross domain success!";


  code Description: @ CrossOrigin annotation is very convenient to use. It can be used on methods or classes. If you do not set the value property or the origins property, all URL / domain access will be allowed by default.

  • The value property can set multiple URL s.
  • The origins property can also set multiple URL s.
  • The maxAge property specifies the maximum duration of the cache before the response is prepared. Is the validity of the probe request.
  • The allowCredentials property indicates whether the user can send and process cookie s. Default is false
  • The allowedHeaders property indicates which request headers are allowed.
  • The methods property indicates the method allowed to request. By default, get, post, head.

2. Implement WebMvcConfigurer

 * @author Full stack learning notes
 * @date 2020/4/21 12:04
 * @description
public class MyWebMvcConfig implements WebMvcConfigurer {
    public void addCorsMappings(CorsRegistry registry) {

  there's nothing to say about this. Just rewrite the addcorsmapping method. Configure the parameters. The parameters are similar to those of the above annotation. This configuration belongs to global configuration, and all configured interfaces follow this rule. The above annotation method only works for classes or methods. Addmapping is set to work for URLs of that format, that is, the path following the URL.

3. Filter configuration

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

 * @author Full stack learning notes
 * @date 2020/4/21 12:49
 * @description
public class Filter {
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:8093 "); / / * indicates that all
        source.registerCorsConfiguration("/**", config); // CORS configuration is valid for all interfaces
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        return bean;


  there is another way to cross domains with filter configuration

package com.example.democrossorigin.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CorssFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "http://localhost:8093");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        chain.doFilter(request, response);
    public void destroy() {
    public void init(FilterConfig filterConfig) throws ServletException {

3. Cross domain test

  we are creating a new SpringBoot web project, and then creating a new index.html in static in the resources folder
The code is as follows

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<div id="test"></div>
<input type="button" value="test data" onclick="getString()"/>

    function getString() {
            success:function (msg) {

  we simulate an ajax request to request our port 8092 and run the new project results

  click test to initiate the request

  if we successfully get the data of another project from one project, our cross domain is successful.

4. Summary:##

  this paper describes the causes, principles and the concept of homology policy of cross domain, and then introduces three ways to solve cross domain in spring boot, which are to use crossorigin annotation to configure Mvc globally, and then to use filter configuration. There are two ways to implement filter, one is to use servlet filter. If you think this article is useful! It's not bad to like it! Your praise is my greatest encouragement and support.

Tags: Java Spring SpringBoot JQuery

Posted on Tue, 21 Apr 2020 02:04:11 -0700 by Big_Ad