SpringBoot解决跨域问题

项目结构

添加WebCorsConfig跨域类,实现WebMvcConfigurer接口,同时加上@Configuration注解

完整代码

package com.mzx.loginlist.config;

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

/**
 * @author Mzx
 * @create 2019-09-15 11:14
 */
@Configuration
public class WebCorsConfig implements WebMvcConfigurer {

    /**
     * 跨域问题解决
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")// 1 允许任何域名使用
                .allowedHeaders("*")// 2 允许任何头
                .allowedMethods("*");// 3 允许任何方法(post、get等)
    }

    /**
     * 配置自定义类 LoginInterceptor 实现拦截登陆
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
//                 .addPathPatterns(new String[]{"/test"});
                .addPathPatterns(new String[]{"/page/allUsers.html"});
//                .addPathPatterns(new String[]{"/findAllUser"});

    }
}

posted @ 2020-02-08 01:30  小马哥是没有感情的  阅读(400)  评论(0编辑  收藏  举报