专业的JAVA编程教程与资源

网站首页 > java教程 正文

Spring Boot Web项目解决CORS跨域问题

temp10 2025-03-23 23:51:11 java教程 8 ℃ 0 评论

在XXXApplication 类中增加ServletComponentScan

@ServletComponentScan

package com.xxx.xxx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;

import java.util.concurrent.Executor;

@ServletComponentScan
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
//@ComponentScan({"com.hc.resume.service"})
public class HelloWordApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloWordApplication.class, args);
    }
}

创建CORSFilter

package com.xxx.xxx;

import cn.hutool.core.util.StrUtil;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;

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

@WebFilter(filterName = "CorsFilter", urlPatterns = {"/*"},asyncSupported = true)
@Order(1)
public class CorsFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,request.getHeader(HttpHeaders.ORIGIN));
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS,"true");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, StrUtil.format("x-token,{}",HttpHeaders.CONTENT_TYPE));
        response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, StrUtil.format("{},{},{}", HttpMethod.GET.name(), HttpMethod.POST.name(),HttpMethod.OPTIONS));

        if(request.getMethod().equals(HttpMethod.OPTIONS.name())){
            response.setStatus(200);
            return;
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}

Spring Boot Web项目解决CORS跨域问题

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表