服务器端实现跨域访问

#跨域# 服务器端实现跨域访问

摘要

服务器端实现跨域访问,不是jsonp,客户端不用做任何变动。

概述

通过Servlet方法中的doOptions方法确定服务器端允许哪些其它域的资源对本方法(get,post)发起请求。

代码实现

Servlet 代码

package servlets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ServletCross extends HttpServlet {

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        if ("http://localhost:63343".equals(req.getHeader("Origin"))) {
            resp.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
//        resp.addHeader("Access-Control-Max-Age", "120"); // in seconds
//        resp.addHeader("Access-Control-Allow-Credentials", "true");
            resp.addHeader("Access-Control-Allow-Methods", "HEAD, GET, OPTIONS, POST");
            resp.addHeader("Access-Control-Allow-Headers", "Content-Type,origin, content-type, accept, x-requested-with");
        }
    }

    protected void doPost(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws javax.servlet.ServletException, IOException {
        doGet(req, resp);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws javax.servlet.ServletException, IOException {
        if (req.getHeader("Origin") != null) {
            resp.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
//            resp.addHeader("Access-Control-Allow-Credentials", "false");
//            resp.setHeader("Connection", "keep-alive");
        }

        resp.setContentType("text/html");
        PrintWriter pw = null;
        try {
            pw = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        pw.write("<h1> hello first servlet!</h1>");
    }


}

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test Cross Domain</title>
    <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>

    <script>

        $(function () {

            $.ajax("http://127.0.0.1:8080/cross", {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: {"data": 1111},
                success: function(data, status, xhr) {
                    console.log("success! data:" + data);
                },
                error: function(xhr, status, error) {
                    console.log("error");
                }

            });
        });
    </script>
</head>
<body>
</body>
</html>

运行查看效果

服务器端所在的域是 http://127.0.0.1:8080
客户端所在的域是 http://localhost:63343

虽然是两个不同的源,但是POST请求可以正常返回200。
表明跨域成功。

但是如果客户端的请求地址是
http://127.0.0.1:63343/test_web/test01/index.html

那么会响应不允许访问
因为服务器端配置的只允许 http://localhost:63343 这一个域可以跨域访问。

需要注意的是
http://localhost:63343
http://127.0.01:63343
http://127.0.0.1:8080
是三个不同的源

参考地址

https://segmentfault.com/a/1190000003710973

源码地址

https://coding.net/u/javacore/p/cross-domain/git