Java后端CORS解决跨域问题

一.  跨域问题是什么?

当前端通过浏览器向后端发送请求,后端向浏览器返回响应时,浏览器对后端响应的校验,就是跨域问题。

二.  为什么会出现跨域问题?

出于浏览器的同源策略,旨在防止恶意网站对用户的其他网站进行未经授权的操作。当前端发出请求的URL和后端响应的URL的协议、域名、端口三者有一个不同时,就会被浏览器拦截。
举个例子,你用自己的前端页面,如:https://www.example.com去访问淘宝的后端URL,https://www.taobao.com,域名不同,被浏览器拦截。怎么办呢?要不给马云打个电话?

三.  怎么解决跨域问题?

这里采用CORS(跨域资源共享)解决跨域问题,这是最正统,也是官方推荐的方法。

1.全局CORS配置:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://example.com") // 允许的源,就是你前端发起请求的URL
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
                .allowedHeaders("*") // 允许的头部
                .allowCredentials(true); // 是否允许发送凭据
    }
}

2.控制器级别CORS配置:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiController {

    @CrossOrigin(origins = "http://example.com")
    @GetMapping("/data")
    public String getData() {
        return "data";
    }
}

3.过滤器配置CORS:

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

public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("已初始化CORS过滤器");// 初始化方法,可以用来读取配置
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // Allow CORS from any origin
        resp.setHeader("Access-Control-Allow-Origin", "*");//指定允许跨域的域名
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");//指定允许的 HTTP 方法
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, token");//指定允许的自定义请求头部
        resp.setHeader("Access-Control-Max-Age", "3600");//浏览器应缓存预检请求(OPTIONS 请求)的结果1h,1h内该源不用再预检,直接发送正式请求

        // Handle preflight requests,预检请求直接返回
        if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        // Continue the request-response chain
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("CORS过滤器已关闭");// 清理资源
    }
}

然后,你需要在 web.xml 文件中注册这个过滤器:

<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>com.example.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

若没有web.xml文件,可在配置类config新建WebConfig来注册:

import com.dairy.filter.CORSFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebConfig {

    @Bean
    public FilterRegistrationBean<CORSFilter> corsFilter() {
        FilterRegistrationBean<CORSFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CORSFilter());
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值