欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-26 11:36:10
springboot 实现跨域访问 无需使用jsonp 在springboot的拦截器中添加respone的头信息即可 @override public...

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/**");
  }
}

总结

以上所述是小编给大家介绍的springboot 实现跨域访问无需使用jsonp的实现代码,希望对大家有所帮助