Home > Java > javaTutorial > What are the ways springboot solves cross-domain issues?

What are the ways springboot solves cross-domain issues?

WBOY
Release: 2023-05-22 15:49:25
forward
823 people have browsed it

What is cross-domain

Cross-domain: refers to the fact that the browser cannot execute scripts from other websites. It is caused by the browser's same-origin policy, which is a security restriction imposed by the browser on JavaScript.
For example: If page a wants to obtain the resources of page b, if the protocols, domain names, ports, and subdomain names of pages a and b are different, the access actions performed will be cross-domain, and the browser
For security reasons, cross-domain access is generally restricted, that is, cross-domain resource requests are not allowed. Note: Cross-domain access restrictions are actually browser restrictions. It is important to understand this

Same origin policy: It means that the protocol, domain name, and port must be the same. Any difference among them will cause cross-domain problems;

springboot solves cross-domain problems Several ways

Method 1. SpringBoot annotation @CrossOrigin

Add the @CrossOrigin annotation directly to the Controller method or class. SpringMVC uses @CrossOrigin usage scenarios that require jdk1.8 Spring4.2

@GetMapping("/hello")
@CrossOrigin
public String hello() {
        return "hello:" + simpleDateFormat.format(new Date());
}
Copy after login

Method 2: Use CorsFilter

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;
@Configuration
public class ConfigConfiguration {
    @Bean
    public CorsFilter CorsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource ub = new UrlBasedCorsConfigurationSource();
        ub.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(ub);
    }
}
Copy after login

Method 3: Custom filter (web filter) method

@Component
public class CustomFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        // 设置允许Cookie
        res.addHeader("Access-Control-Allow-Credentials", "true");
        // 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求
        res.addHeader("Access-Control-Allow-Origin", "*");
        // 设置允许跨域请求的方法
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        // 允许跨域请求包含content-type
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (((HttpServletRequest) servletRequest).getMethod().equals("OPTIONS")) {
            servletResponse.getWriter().println("ok");
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
Copy after login

Method 4: Implement the addCorsMappings method in WebMvcConfigurer

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 匹配所有的路径
                .allowCredentials(true) // 设置允许凭证
                .allowedHeaders("*")   // 设置请求头
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 设置允许的方式
                .allowedOriginPatterns("*");
    }
}
Copy after login

Method 5: Use nginx as a dynamic proxy

The above is the detailed content of What are the ways springboot solves cross-domain issues?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template