28、Springboot项目解决跨域问题的几种方案

1、在Springboot启动类中解决跨越问题

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class BasicApplication extends SpringBootServletInitializer {

    private final String EXPOSE_HEADER = "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Token";

    public static void main(String[] args) {
        SpringApplication.run(BasicApplication.class, args);
    }

    /**
     * 使用外部Tomcat服务器,该配置尤其重要
     * @param builder
     * @return
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(BasicApplication.class);
    }

    /**
     * 创建跨域配置项
     * @return
     */
    private CorsConfiguration buildCorsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addExposedHeader(EXPOSE_HEADER);
        return corsConfiguration;
    }

    /**
     * 创建跨域过滤器
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildCorsConfig());
        return new CorsFilter(source);
    }
}

2、在Controller类上加注解方式,实现细粒度跨域访问控制

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/home")
@CrossOrigin(origins = "*", maxAge = 3600)
public class HomeController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}

3、创建过滤器,解决跨域访问问题

import org.springframework.stereotype.Component;

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

/**
 * 解決前端跨域問題
 */
@Component
public class OriginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

4、以JSONP方式,解决跨域问题

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;

/**
 * 解决跨域请求问题
 *
 * 前端跨域访问示例代码
 *      $.ajax({
 *             type:'post',
 *             url:'http://localhost:8003/jsonp/testJsonp',
 *             dataType:'jsonp',
 *             jsonpCallback:"callback",
 *             success:function (data) {
 *                 ...
 *             },
 *             error:function (err) {
 *                 ...
 *             }
 *       });
 */
@ControllerAdvice(basePackages = "com.sample.controller")
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {

    public JsonpAdvice() {
        super("callback","jsonp");
    }
}

【注意】其中 basePackages = "com.sample.controller" 的值要根据项目实际情况,填写controller的真实包名,才能对相应包名下的控制器请求实施拦截

5、Nginx方向代理解决跨域访问

server {
        listen       80; #监听80端口,可以改成其他端口
        server_name  localhost; # 当前服务的域名
        
        # 反向代理所有/apis开头的访问请求
        location /apis {
            proxy_pass   http://localhost:8080;
        }
}

实际项目中就用到过这些,以后再遇到其他情况,再陆续添加进来,希望对正在阅读的您有所帮助,也加深自己记忆

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Java)