在SpringBoot中使用Filter过滤器解决跨域问题

1.在SpringBoot的启动类中加上@ServletComponentScan注解,使@WebFilter注解启用
2.代码:

package com.walmart.ecrecon_server;

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

/**
 * Created by vn0790t on 2020/5/7.
 */
@WebFilter(filterName = "webContextFilter",urlPatterns = "/*")
public class WebContextFilter implements Filter{

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

    }

    @Override
    public void doFilter(ServletRequest re, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) re;
        //解决跨域的问题
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Expose-Headers","*");
        response.setHeader("Access-Control-Allow-Methods","*");
        response.setHeader("Access-Control-Max-Age", "18000L");

        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}

你可能感兴趣的:(java技术)