Jimoy 发表于 2024-3-31 11:02:01

Java实现跨域的5种方式


1. 返回新的 CorsFilter(全局跨域)

package org.chuancey.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;



@Configuration
public class GlobalCorsConfig {


    @Bean

    public CorsFilter corsFilter() {

      //1. 添加 CORS配置信息
      CorsConfiguration config = new CorsConfiguration();

      // 放行哪些原始域
      config.addAllowedOrigin("*");

      // 是否发送 Cookie
      config.setAllowCredentials(true);

      // 放行哪些请求方式
      config.addAllowedMethod("*");

      // 放行哪些原始请求头部信息

      config.addAllowedHeader("*");

      // 暴露哪些头部信息

      config.addExposedHeader("*");

      //2. 添加映射路径

      UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();

      corsConfigurationSource.registerCorsConfiguration("/**",config);

      //3. 返回新的CorsFilter

      return new CorsFilter(corsConfigurationSource);

    }



}
2. 重写 WebMvcConfigurer(全局跨域)

package org.chuancey.config;

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



@Configuration

public class CorsConfig implements WebMvcConfigurer {



    @Override

    public void addCorsMappings(CorsRegistry registry) {

      registry.addMapping("/**")

                //放行哪些原始域

                .allowedOrigins("*")

                .allowedHeaders("*")

                // 是否发送Cookie

                .allowCredentials(true)

                .allowedMethods("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH")

                .maxAge(3600);

    }



    @Override

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

      registry.addResourceHandler("/**")

                .addResourceLocations("classpath:/static/");

      registry.addResourceHandler("swagger-ui.html")

                .addResourceLocations("classpath:/META-INF/resources/");

      registry.addResourceHandler("doc.html")

                .addResourceLocations("classpath:/META-INF/resources/");

      registry.addResourceHandler("/webjars/**")

                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }

}

3. 使用注解 (局部跨域)

在控制器(类上)上使用注解 @CrossOrigin,表示该类的所有方法允许跨域。
@RestController
@CrossOrigin(origins = "*")
public class VerificationController {

}
在方法上使用注解 @CrossOrigin
@PostMapping("/check/phone")
    @CrossOrigin(origins = "*")
    public boolean checkPhoneNumber(@RequestBody @ApiParam VerificationPojo verification) throws BusinessException {
      return false;

    }

4. 手动设置响应头(局部跨域)
使用 HttpServletResponse 对象添加响应头(Access-Control-Allow-Origin)来授权原始域,这里 Origin的值也可以设置为 “*”,表示全部放行。
@RequestMapping("/home")
public String home(HttpServletResponse response) {
    response.addHeader("Access-Allow-Control-Origin","*");
    return "home";

}

5. 使用自定义filter实现跨域
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;


@Slf4j

@Configuration

@WebFilter(filterName = "accessFilter", urlPatterns = "/*")

public class MyCorsFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", "*");

    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

    response.setHeader("Access-Control-Max-Age", "3600");

    response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");

    chain.doFilter(req, res);

}



public void init(FilterConfig filterConfig) {log.info("AccessFilter过滤器初始化!");}


public void destroy() {}

}

xml使自定义Filter生效方式
<!-- 跨域访问 START-->

<filter>

<filter-name>CorsFilter</filter-name>

<filter-class>org.chuancey.filter.MyCorsFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>CorsFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<!-- 跨域访问 END-->




页: [1]
查看完整版本: Java实现跨域的5种方式