首页 > 开发 > Java > 正文

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

2024-07-14 08:42:27
字体:
来源:转载
供稿:网友

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;  }@Configurationpublic 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的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对VeVb武林网网站的支持!


注:相关教程知识阅读请移步到JAVA教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表