美文网首页
SpringBoot解决跨域问题

SpringBoot解决跨域问题

作者: 超音速6 | 来源:发表于2020-04-06 18:28 被阅读0次

    SpringBoot启动类

    import com.example.filter.CrosFilter;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
     
    @SpringBootApplication
    public class exampleApplication {
     
        public static void main(String[] args) {
            SpringApplication.run(exampleApplication.class, args);
        }
     
        /**
         * 配置跨域访问的过滤器
         * @return
         */
        @Bean
        public FilterRegistrationBean registerFilter(){
            FilterRegistrationBean bean = new FilterRegistrationBean();
            bean.addUrlPatterns("/*");
            bean.setFilter(new CrosFilter());
            return bean;
        }
    }
    

    过滤器

    import javax.servlet.*;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
     
    public class CrosFilter implements javax.servlet.Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
     
        }
     
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse) servletResponse;
            //*号表示对所有请求都允许跨域访问
            res.addHeader("Access-Control-Allow-Origin", "*");
            res.addHeader("Access-Control-Allow-Methods", "*");
            filterChain.doFilter(servletRequest, servletResponse);
        }
     
        @Override
        public void destroy() {
     
        }
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot解决跨域问题

          本文链接:https://www.haomeiwen.com/subject/hdabphtx.html