首页 > 开发 > Java > 正文

详解springboot设置cors跨域请求的两种方式

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

1、第一种:

public class CorsFilter extends OncePerRequestFilter {  static final String ORIGIN = "Origin";  protected void doFilterInternal(    HttpServletRequest request,     HttpServletResponse response,     FilterChain filterChain) throws ServletException, IOException {      String origin = request.getHeader(ORIGIN);      response.setHeader("Access-Control-Allow-Origin", "*");//* or origin as u prefer    response.setHeader("Access-Control-Allow-Credentials", "true");    response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE");    response.setHeader("Access-Control-Max-Age", "3600");    response.setHeader("Access-Control-Allow-Headers", "content-type, authorization");      if (request.getMethod().equals("OPTIONS"))      response.setStatus(HttpServletResponse.SC_OK);    else       filterChain.doFilter(request, response);    }}@Beanpublic CorsFilter corsFilter() throws Exception {  return new CorsFilter();}http  .addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class)  .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)  .headers()  .cacheControl();

2、第二种:

@Configurationpublic class CorsConfig {  @Bean  public FilterRegistrationBean corsFilter() {    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();    CorsConfiguration config = new CorsConfiguration();    config.setAllowCredentials(true);    // 设置你要允许的网站域名,如果全允许则设为 *    config.addAllowedOrigin("http://localhost:4200");    // 如果要限制 HEADER 或 METHOD 请自行更改    config.addAllowedHeader("*");    config.addAllowedMethod("*");    source.registerCorsConfiguration("/**", config);    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));    // 这个顺序很重要哦,为避免麻烦请设置在最前    bean.setOrder(0);    return bean;  }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VeVb武林网。


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