There are three methods for Springboot to process CORS cross domain requests. Java intermediate interview contains answers

First give a familiar error reporting information to make you feel at home~

Access to XMLHttpRequest at 'http://192.168.1.1:8080/app/easypoi/importExcelFile' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

1, What is CORS?

==========

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

It adds a special header [access control allow Origin] to the server to tell the client about the cross domain restrictions. If the browser supports CORS and determines that Origin passes, it will allow XMLHttpRequest to initiate cross domain requests.

CORS Header

  • Access-Control-Allow-Origin: http://www.xxx.com

  • Access-Control-Max-Age: 86400

  • Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE

  • Access-Control-Allow-Headers: content-type

  • Access-Control-Allow-Credentials: true

Interpretation of meaning:

CORS Header propertiesexplain
Access-Control-Allow-Originallow http://www.xxx.com Domain (self setting, here is only an example) initiates cross domain requests
Access-Control-Max-AgeIt is set at 86400 seconds and no pre verification request needs to be sent
Access-Control-Allow-MethodsSet the method to allow cross domain requests
Access-Control-Allow-HeadersAllow cross domain requests to contain content type
Access-Control-Allow-CredentialsSet allow cookies

2, SpringBoot cross domain request processing

====================

Method 1: directly adopt the annotation @ CrossOrigin of SpringBoot (also supports spring MVC)

In a simple and crude way, the Controller layer can add this annotation to the classes or methods that need to cross domain

/**

 * Created with IDEA

 *

 * @Author Chensj

 * @Date 2020/5/8 10:28

 * @Description xxxx Control layer

 * @Version 1.0

 */

@RestController

@CrossOrigin

@RequestMapping("/situation")

public class SituationController extends PublicUtilController {



    @Autowired

    private SituationService situationService;

    // log information

    private static Logger LOGGER = Logger.getLogger(SituationController.class);







}

However, each Controller has to be added. It's too troublesome. What should we do? Add it to the Controller public parent class (PublicUtilController), and all controllers can inherit.

/**

 * Created with IDEA

 *

 * @Author Chensj

 * @Date 2020/5/6 10:01

 * @Description

 * @Version 1.0

 */

@CrossOrigin

public class PublicUtilController {



    /**

     * Public paging parameter sorting interface

     *

     * @param currentPage

     * @param pageSize

     * @return

     */

    public PageInfoUtil proccedPageInfo(String currentPage, String pageSize) {



        /* paging */

        PageInfoUtil pageInfoUtil = new PageInfoUtil();

        try {

            /*

             * Converting a string to an integer is risky. The string is a and cannot be converted to an integer

             */

            pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));

            pageInfoUtil.setPageSize(Integer.valueOf(pageSize));

        } catch (NumberFormatException e) {

        }

        return pageInfoUtil;

    }



}

**Of course, although it refers to SpringBoot and spring MVC, it is required in spring 4 2 and above** In addition, if the spring MVC Framework version is inconvenient to modify, You can also modify tomcat's web XML configuration file, please refer to another blog post (the same goes for nginx)

Spring MVC @ CrossOrigin usage scenario requirements

  • jdk1.8+
  • Spring4.2+

Method 2: processing cross domain requests

Add a configuration class, crossoriginconfig java. Inherit the WebMvcConfigurerAdapter or implement the WebMvcConfigurer interface. Don't worry about anything else. The configuration will be read automatically when the project is started.

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.CorsRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;



/**

 * AJAX Request cross domain

 * @author Mr.W

 * @time 2018-08-13

 */

@Configuration

public class CorsConfig extends WebMvcConfigurerAdapter {

    static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };

    @Override

    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS).maxAge(3600);

    }

Method 3: filter is adopted

Add a configuration class in the same way. Add a CORSFilter class and implement the Filter interface. Don't worry about anything else. Cross domain interception will be filtered when the interface is called.

summary

Ant interview pays more attention to the foundation, so those basic skills of Java must be solid. The working environment of ants is still very good, because I meet the stability guarantee department, and there are many separate groups. What is class 1 in three years, I feel very young. The basic level of the interviewers is quite high, basically above P7. In addition to the foundation, they also asked a lot of questions about architecture design, and the harvest is still very big.

Data collection method: stamp here

After this interview, I also found the need for real interviews with large factories through some channels, mainly including ant financial, pinduoduo, Alibaba cloud, Baidu, vipshop, Ctrip, Fengchao technology, Lexin, softcom power, OPPO, Yinsheng payment, China Ping An and other early, intermediate and advanced Java interview questions, with super detailed answers. I hope I can help you.

, because I'm in the stability assurance department, and there are many separate groups. What's class 1 for three years, I feel very young. The basic level of the interviewers is quite high, basically above P7. In addition to the foundation, they also asked a lot of questions about architecture design, and the harvest is still very big.

Data collection method: stamp here

After this interview, I also found the need for real interviews with large factories through some channels, mainly including ant financial, pinduoduo, Alibaba cloud, Baidu, vipshop, Ctrip, Fengchao technology, Lexin, softcom power, OPPO, Yinsheng payment, China Ping An and other early, intermediate and advanced Java interview questions, with super detailed answers. I hope I can help you.

Keywords: Java Interview Programmer

Added by opticmike on Tue, 21 Dec 2021 03:22:55 +0200