美文网首页
SpringBoot应用配置允许跨域访问

SpringBoot应用配置允许跨域访问

作者: jeffrey_hjf | 来源:发表于2020-03-02 01:46 被阅读0次

方式一:添加全局跨域配置类

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;

/**
 * @author: jeffrey
 * @date: 2020/3/2
 * @description: 跨域配置类
 * @modified By:
 * @version: 1.0.0
 */
@Configuration
public class GlobalCorsConfig {
    private CorsConfiguration addCorsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //请求常用的三种配置,*代表允许所有,当时你也可以自定义属性(比如header只能带什么,只能是post方式等等)
        //允许任何域名
        corsConfiguration.addAllowedOrigin("*");
        //允许任何头
        corsConfiguration.addAllowedHeader("*");
        //允许任何方法(post、get等)
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //注册
        source.registerCorsConfiguration("/**", addCorsConfig());
        return new CorsFilter(source);
    }
}

方式二:在controller类上添加@CrossOrigin注解

import com.jeffrey.template.springboot.base.util.StringUtil;
import org.springframework.web.bind.annotation.*;

/**
 * @author: jeffrey
 * @date: 2020/3/2
 * @description: 测试Controller
 * @modified By:
 * @version:
 */
@RestController
public class TestController {

    @GetMapping("/test/{id}")
    @CrossOrigin(origins = {"*"}, allowedHeaders = {"*"}, methods = {})
    public String test(@PathVariable(name = "id") String id, @RequestParam("name") String name) {
        return id + "--" + name + StringUtil.getUUID();
    }
}

方式三:使用Filter (不推荐)

import javax.servlet.*;  
import javax.servlet.http.HttpServletResponse;  
import java.io.IOException;  

@Component  
public class CorsFilter 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");  
        response.setHeader("Access-Control-Max-Age", "3600");  
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");   
        chain.doFilter(req, res);  
    }  
    public void init(FilterConfig filterConfig) {}  
    public void destroy() {}  
}

相关文章

网友评论

      本文标题:SpringBoot应用配置允许跨域访问

      本文链接:https://www.haomeiwen.com/subject/kxljkhtx.html