1. 程式人生 > >SpringBoot多跨域請求的支援(JSONP)

SpringBoot多跨域請求的支援(JSONP)

在我們做專案的過程中,有可能會遇到跨域請求,所以需要我們自己組裝支援跨域請求的JSONP資料,而在4.1版本以後的SpringMVC中,為我們提供了一個AbstractJsonpResponseBodyAdvice的類用來支援jsonp的資料(SpringBoot接收解析web請求是依賴於SpringMVC實現的)。下面我們就看一下怎麼用AbstractJsonpResponseBodyAdvice來支援跨域請求。

使用AbstractJsonpResponseBodyAdvice來支援跨域請求很簡單,只需要繼承這個類就可以了。具體程式碼如下:

package com.zkn.learnspringboot.config;

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

/**
 * Created by wb-zhangkenan on 2016/12/1.
 */
@ControllerAdvice(basePackages = "com.zkn.learnspringboot.web.controller")
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice{

    public JsonpAdvice() {

        super("callback","jsonp");
    }
}
下面我們寫個類來測試一下:
package com.zkn.learnspringboot.web.controller;

import com.zkn.learnspringboot.domain.PersonDomain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by wb-zhangkenan on 2016/12/1.
 */
@RestController
@RequestMapping("/jsonp")
public class JsonpTestController {
    @Autowired
    private PersonDomain personDomain;

    @RequestMapping(value = "/testJsonp",produces = MediaType.APPLICATION_JSON_VALUE)
    public PersonDomain testJsonp(){

        return personDomain;
    }
}
當我們傳送請求為:http://localhost:8003/jsonp/testJsonp的時候,結果如下:


當我們傳送的請求為:http://localhost:8003/jsonp/testJsonp?callback=callback的時候,結果如下所示:


看到區別了嗎?當我們在請求引數中新增callback引數的時候,返回的資料就是jsonp的,當我們請求引數中不帶callback的時候,返回的資料是json的。可以讓我們方便的靈活運用。下面再奉上一個jsonp的完整案例。

前臺頁面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="resources/js/jquery-2.1.4.min.js" type="text/javascript"></script>
</head>
<body>
<input type="button" value="測試jsonp請求" onclick="testJsonp()" />
<script type="text/javascript">
    function testJsonp() {
        $.ajax({
            type:'get',
            url:'http://localhost:8003/jsonp/testJsonp',
            dataType:'jsonp',
            jsonp:"callback",
            success:function (data) {
                alert(data.userName+"  "+data.passWord);
            },
            error:function (err) {
                alert('出現錯誤了!!!');
            }
        });
    }
</script>
</body>
</html>
後臺程式碼1:
package com.zkn.learnspringmvc.news.controller;

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

/**
 * Created by zkn on 2016/12/3.
 */
@Controller
public class JsonpTestController {

    @RequestMapping("testJsonp")
    public String testJsonp(){

        return "jsonp";
    }
}
下面我們傳送請求如下:http://localhost:8080/LearnSpringMvc/testJsonp

當我們點選測試jsopn請求這個按鈕的時候,效果如下:


我們成功的實現了一個跨越的請求。更詳細的請求資訊如下: