• 【Java Web开发学习】跨域请求


    【Java Web开发学习】跨域请求

    =================================================

    1、使用jsonp

    =================================================

    代码很简单不做解释
    json和jsonp的区别阅读   https://kb.cnblogs.com/page/139725/

    package ycx.crossdomain.controller;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.util.StringUtils;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.PrintWriter;
    import java.util.HashMap;
    import java.util.Map;
    
    @RestController
    public class IndexController {
    
        @RequestMapping("/")
        public void index(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("status", 200);
            dataMap.put("message", "OK");
            dataMap.put("data", "hello world");
    
            ObjectMapper mapper = new ObjectMapper();
            String data = mapper.writeValueAsString(dataMap);
    
            PrintWriter out = response.getWriter();
            String callback = request.getParameter("callback");
            if (StringUtils.isEmpty(callback)) {
                out.print(data);
            } else {
                out.print(callback + "(" + data + ")");
            }
            out.flush();
            out.close();
        }
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>jsonp</title>
        <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
    </head>
    <body>
    <script>
        // has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
        // $.ajax({
        //     type: "GET",
        //     async: false,
        //     url: "http://localhost:9902",
        //     success: function (result) {
        //         console.dir(result);
        //     },
        //     error: function (e) {
        //         console.dir(e);
        //     }
        // });
    
    
        $.ajax({
            type: "GET",
            async: false,
            url: "http://localhost:9902",
            dataType: "jsonp",
            jsonp: "callback",
            jsonpCallback:"handler",
            success: function (result) {
                console.dir(result);
            },
            error: function (e) {
                console.dir(e);
            }
        });
    </script>
    </body>
    </html>
  • 相关阅读:
    Annotation
    bulid tools
    Git&Version Control
    uri&url
    HTTP &RFC
    git创建新分支
    git忽略提交文件
    redis集群搭建
    java中的线程安全是什么:
    Spring事务传播机制与隔离级别
  • 原文地址:https://www.cnblogs.com/yangchongxing/p/11454362.html
Copyright © 2020-2023  润新知