SpringBoot解决跨域问题

方法一: 创建一个filter解决跨域,此方法也支持springmvc。

@Component
public class SimpleCORSFilter 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, HEAD");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
} 

方法二:基于继承WebMvcConfigurerAdapter或者实现WebMvcConfigurer接口配置加入Cors的跨域,此方法常用于springboot。

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

@Configuration 
public class CorsConfig extends WebMvcConfigurerAdapter { 
    @Override 
    public void addCorsMappings(CorsRegistry registry) { 
        registry.addMapping("/**") 
                .allowedOrigins("*") 
                .allowCredentials(true) 
                .allowedMethods("GET", "POST", "DELETE", "PUT") 
                .maxAge(3600); 
    } 
}
import com.common.constant.TokenConstants;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
                // 设置允许跨域的路由
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许证书(cookies)
                .allowCredentials(true)
                // 设置允许的方法
                .allowedMethods("*")
                // 跨域允许时间
                .maxAge(3600);
    }
} 

方法三:设置特别控制层允许跨域

@CrossOrigin(origins = "http://192.168.1.10:8080", maxAge = 3600)
@RequestMapping("/index")
@RestController
public class IndexController{
}

@CrossOrigin这个注解在controller类中使用,就可以指定该controller中所有方法都能处理来自http:19.168.1.10:8080中的请求。

posted @ 2022-01-18 15:32  江南大才子  阅读(915)  评论(0编辑  收藏  举报