Ajax:ajax跨域解决方案代理機制原理及實現

dengfengling999 2022-07-24 00:09:03 阅读数:112

ajaxajax解决方案解决方案

目錄:

(1)ajax跨域解决方案之代理機制實現原理

(2)ajax跨域解决方案之代理機制的代碼實現


 

(1)ajax跨域解决方案之代理機制實現原理

讓ajax請求訪問servlet,可以讓ajax請求跨域,通過直接本應用中的資源servlet,ajax可以不跨域訪問本應用中的servlet,讓java程序發送Get,Post請求,來訪問2號服務器中的的servlet

 

用java代碼模擬瀏覽器的行為,就好比在瀏覽器地址欄輸入地址敲回車一樣

首先把架包導入:創建lib目錄,複制進去  選中右鍵Add as library

HttpClientSendGet:

package com.bjpowernode.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpClientSendGet {
public static void main(String[] args) throws Exception {
// 使用java代碼去發送HTTP get請求
// 目標地址
//String url = "https://www.baidu.com";
String url = "http://localhost:8081/b/hello";
HttpGet httpGet = new HttpGet(url);
// 設置類型 "application/x-www-form-urlencoded" "application/json"
httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
//System.out.println("調用URL: " + httpGet.getURI());
// httpClient實例化
CloseableHttpClient httpClient = HttpClients.createDefault();
// 執行請求並獲取返回
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
//System.out.println("返回狀態碼:" + response.getStatusLine());
// 顯示結果
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
String line = null;
StringBuffer responseSB = new StringBuffer();
while ((line = reader.readLine()) != null) {
responseSB.append(line);
}
System.out.println("服務器響應的數據:" + responseSB);
reader.close();
httpClient.close();
}
}

 運行:

 (2)ajax跨域解决方案之代理機制的代碼實現

b站點創建Servlet:

TargetServlet:

package com.bjpowernode.b.web.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/target")
public class TargetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 響應一個json字符串。
response.getWriter().print("{\"username\":\"jackson\"}");
}
}

 a站點需要servlet,首先需要加入servlet依賴:

引入架包:httpclient架包

 

 

 

ProxyServlet:發送get請求,訪問b站點TargerServlet,請求響應回來數據在進行響應

 

package com.bjpowernode.javaweb.servlet;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@WebServlet("/proxy")
public class ProxyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 通過httpclient組件,發送HTTP GET請求,訪問 TargetServlet
HttpGet httpGet = new HttpGet("http://localhost:8081/b/target");
httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse resp = httpClient.execute(httpGet);
HttpEntity entity = resp.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
String line = null;
StringBuffer responseSB = new StringBuffer();
while ((line = reader.readLine()) != null) {
responseSB.append(line);
}
reader.close();
httpClient.close();
// b站點響應回來的數據
response.getWriter().print(responseSB);
}
}

ajax5.html:發送ajax請求:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用代理機制完成ajax跨域訪問</title>
</head>
<body>
<script type="text/javascript">
// ES6當中的有一個新語法:箭頭函數。
window.onload = () => {
document.getElementById("btn").onclick = () => {
// 發送ajax請求
// 1.創建核心對象
const xmlHttpRequest = new XMLHttpRequest(); // const可以聲明變量。(可以自己研究一下:var let const聲明變量時有什麼區別)
// 2.注册回調函數
xmlHttpRequest.onreadystatechange = () => {
if (xmlHttpRequest.readyState == 4) {
// 這裏也可以使用區間的方式,因為狀態碼是200~299都是正常響應結束。
if (xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) {
document.getElementById("mydiv").innerHTML = xmlHttpRequest.responseText
}
}
}
// 3.開啟通道
xmlHttpRequest.open("GET", "/a/proxy", true)
// 4.發送請求
xmlHttpRequest.send()
}
}
</script>
<button id="btn">使用代理機制解决ajax跨域訪問</button>
<div id="mydiv"></div>
</body>
</html>

點擊按鈕:

 

 

 

版权声明:本文为[dengfengling999]所创,转载请带上原文链接,感谢。 https://gsmany.com/2022/205/202207240008267276.html