Springboot 实现跨域访问 无需使用jsonp

在springboot的拦截器中添加respone的头信息即可

 @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        //String origin = (String) request.getRemoteHost()+":"+request.getRemotePort();
        response.addHeader("Access-Control-Allow-Origin", "*");
        //System.out.println("Access-Control-Allow-Origin");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        //System.out.println("Access-Control-Allow-Methods");
        response.addHeader("Access-Control-Max-Age", "3600");
        //System.out.println("Access-Control-Max-Age");
        response.addHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        //System.out.println("Access-Control-Allow-Headers");
        response.addHeader("Access-Control-Allow-Credentials","true");
        //System.out.println("Access-Control-Allow-Credentials");
        String api_key = request.getParameter("api_key");
        String api_secret = request.getParameter("api_secret");
;
            if (check(api_key,api_secret)){
                return true;
            }
           response.sendError(400,"api_key or api_secret are error");
            return false;
    }

 

 

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {


    @Bean
    APIIntercepter apiIntercepter() {
        return new APIIntercepter();
    }



    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加一个拦截器,连接以/v1为前缀的 url路径
        registry.addInterceptor(loginIntercepter()).addPathPatterns("/admin/**");
        registry.addInterceptor(apiIntercepter()).addPathPatterns("/v1/**");

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值