【spring boot】SpringBoot初学(9.1)– 简单配置corsFilter对跨域请求支持

前言

  只是简单的配置实现了cors,并没有讲任何东西。(有兴趣的可看: CORS 跨域 实现思路及相关解决方案

  github: https://github.com/vergilyn/SpringBootDemo

  代码位置:

image

  origin:表示服务端程序(默认为:127.0.0.1:8080)。其中有CorsFilter,且allow-origina配置为http://127.0.0.1:8081。

  client_a/client_b:分别是客户端。其中client_a的端口号是8081,client_b的端口号是8082.

 

@SpringBootApplication
public class CorsOriginApplication {
    public final static String CORS_ADDRESS = "127.0.0.1";

    public static void main(String[] args) {
        SpringApplication.run(CorsOriginApplication.class,args);
    }
}
CorsOriginApplication.java
@Controller
@RequestMapping("/cors")
public class CorsOriginController {

    /**
     * 如果CrosFilter中配置有Access-Control-Allow-Origin, 则CrossOrigin无效。
     * 否则, 以@CrossOrigin为准。
     * @return
     */
    @CrossOrigin(origins = "http://127.0.0.1:8082")
    @RequestMapping("/get")
    @ResponseBody
    public Map<String,Object> get(){
        return Constant.map;
    }
}
@Configuration
@WebFilter(urlPatterns = "/cors")
public class CorsFilter extends OncePerRequestFilter {
    private final static String ALLOWORIGIN_CORS_A = "http://127.0.0.1:8081";
    private final static String ALLOWORIGIN_CORS_b = "http://127.0.0.1:8082";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // Access-Control-Allow-Origin: 指定授权访问的域
        response.addHeader("Access-Control-Allow-Origin", ALLOWORIGIN_CORS_A);  //此优先级高于@CrossOrigin配置

        // Access-Control-Allow-Methods: 授权请求的方法(GET, POST, PUT, DELETE,OPTIONS等)
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

        response.addHeader("Access-Control-Allow-Headers", "Content-Type");

        response.addHeader("Access-Control-Max-Age", "1800");//30 min
        filterChain.doFilter(request, response);
    }
}

注意:

  如果在CorsFilter中配置有"Access-Control-Allow-Origin", 则controller中方法注解@CrossOrigin失效。(即filter的优先级高于@CrossOrigin方法注解)

 

Cors A:

@SpringBootApplication
@Controller
public class CorsAApplication implements EmbeddedServletContainerCustomizer {
    private static int CORS_A_PORT = 8081;

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(CorsAApplication.class);
        app.run(args);
    }

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(CORS_A_PORT);
    }

    @RequestMapping("corsA")
    public String index(Model model){
        model.addAttribute("port",CORS_A_PORT);
        model.addAttribute("address", CorsOriginApplication.CORS_ADDRESS);
        return "cors/corsA_index";
    }
}

corsA_index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <script type="text/javascript" src="./static/common/jquery-2.1.4.js"></script>
    <title>cors client_a</title>
    <script type="text/javascript">

        /*<![CDATA[*/
        function corsFilter() {
            var url = "http://localhost:8080/cors/get";
            $.ajax({
                type: 'get',
                url: url,
                data: {},
                success: function (r) {
                    $("#result").text(JSON.stringify(r));
                },
                error: function (err) {
                    console.info(err);
                    alert('error!');
                }
            });
        }
        /*]]>*/
    </script>
</head>
<body>
<h4>cors client_a</h4>
<p th:text="'server.address: ' + ${address}"/>
<p th:text="'server.port: ' + ${port}"/>
<p>cors配置: allowOrigin = "http://127.0.0.1:8081", 所以此页面可以得到结果!</p>

<input type="button" value="request" onclick="corsFilter()"/><br/>
<h5>结果:</h5>
<p id="result"></p>
</body>
</html>

 

Cors B:

@SpringBootApplication
@Controller
public class CorsBApplication implements EmbeddedServletContainerCustomizer {
    private static int CORS_B_PORT = 8082;

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(CorsBApplication.class);
        app.run(args);
    }

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(CORS_B_PORT);
    }

    @RequestMapping("corsB")
    public String index(Model model){
        model.addAttribute("port",CORS_B_PORT);
        model.addAttribute("address", CorsOriginApplication.CORS_ADDRESS);
        return "cors/corsB_index";
    }
}

corsB_index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <script type="text/javascript" src="./static/common/jquery-2.1.4.js"></script>
    <title>cors client_b</title>
    <script type="text/javascript">

        /*<![CDATA[*/
        function corsFilter() {
            var url = "http://localhost:8080/cors/get";
            $.ajax({
                type: 'get',
                url: url,
                data: {},
                success: function (r) {
                    $("#result").text(JSON.stringify(r));
                },
                error: function (err) {
                    console.info(err);
                    $("#errMsg").css("display","block");
                    alert('error!');

                }
            });
        }
        /*]]>*/
    </script>
</head>
<body>
<h4>cors client_b</h4>
<p th:text="'server.address: ' + ${address}"/>
<p th:text="'server.port: ' + ${port}"/>
<p>cors配置: allowOrigin = "http://127.0.0.1:8081", 所以此页面<font color="red">无法得到结果!</font></p>

<input type="button" value="request" onclick="corsFilter()"/><br/>
<h5>结果:</h5>
<p id="result"></p>

<h5>错误描述:</h5>
<p id="errMsg" style="display: none">
    已拦截跨源请求:同源策略禁止读取位于 http://localhost:8080/cors/get 的远程资源。(原因:CORS 头 'Access-Control-Allow-Origin' 不匹配 'http://127.0.0.1:8081')。
</p>
</body>
</html>

结果演示:

1. 127.0.0.1:8081/corsA可以正确的请求"http://localhost:8080/cors/get"并正确得到返回的结果

image

2. 127.0.0.1:8082/corsB可以正确的请求"http://localhost:8080/cors/get"但无法正确得到请求结果

image

image

posted @ 2017-04-16 22:19  淡丶无欲  阅读(12429)  评论(0编辑  收藏  举报