Java 后端跨域处理

Java 后端跨域处理

  • 前言
  • 拦截器处理跨域

前言

什么是跨域啥的,就不说,不管是理论还是解决方案分析,网上都很多,所以直接上代码

拦截器处理跨域

拦截器返回值中添加跨域处理

CorsInterceptor.java

@Component
public class CorsInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 添加跨域CORS
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization,token");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        return true;
    }
}

注册拦截器

CorssDomainConfig.java

@Configuration
public class CorssDomainConfig implements WebMvcConfigurer {

    @Autowired
    private CorsInterceptor corsInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(corsInterceptor);
        registration.addPathPatterns("/**");
    }

}

你可能感兴趣的:(#,Java,工具封装,CORS,跨域处理,跨域,java)