后端实现跨域的几种方案

cros是前后端交互后的产物,解决方案:nginx前端或者后端或者浏览器端解决

后端控制台也是可以显示日志的,但需要将 logging.logging.root 的日志级别改为debug

方案一:Filter实现跨域

手动注入

在 com.dh.manager.ManagerApplication 中 添加允许跨域方法

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}

可选择重写CorsFilter 类

package com.dh.manager.configurer.cros;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author cl
 * @date 2023-04-28 16:42:17
 */
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 设置允许跨域请求的域名
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 设置允许跨域请求的方法
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        // 设置允许跨域请求的头部信息
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, X-File-Name");
        chain.doFilter(request, httpResponse);
    }

    @Override
    public void destroy() {
    }
}

自动注入

注意:如果有多个过滤器的情况,请注意优先级,@Order(Ordered.HIGHEST_PRECEDENCE),同等优先级的情况下,先后顺序不确定(可能是按照名称排序)

在 com.dh.manager.ManagerApplication 上添加 @ServletComponentScan 注解

自定义过滤类

package com.dh.manager.configurer.cros;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

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

/**
 * @author cl
 * @date 2023-04-28 16:42:17
 */
@WebFilter(filterName = "CorsFilter", urlPatterns = "/*")
@Component
// 针对 UnLoginFilter 过滤器提前 return 导致无法走到这里的解决方案(让这个过滤器先走)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("com.wmx.servlet.SystemFilter -- 系统启动...");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        System.out.println("com.wmx.servlet.SystemFilter -- 过滤器放行前...." + request.getRequestURL());
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 项目中含有多个过滤器时使用
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            response.getWriter().write("OPTIONS returns OK");
            return;
        }
        chain.doFilter(req, res);
        System.out.println("com.wmx.servlet.SystemFilter -- 过滤器返回后...." + request.getRequestURL());
    }

    @Override
    public void destroy() {
        System.out.println("com.wmx.servlet.SystemFilter -- 系统关闭...");
    }

}

重写已有过滤器

package com.dh.manager.configurer.cros;


import com.dh.manager.interceptor.UnLoginFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;


@Component
public class MyUnLoginFilter extends UnLoginFilter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        super.init(filterConfig);
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("重写成功了");
        super.doFilter(request,response,chain);
    }

}

你可能感兴趣的:(1024程序员节)