js自動訪問數據庫
maven依賴
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
Servlet
用的三層架構,service,dao層就不寫了,用的是C3P0連接池,mysql為數據庫
最后返回的是一個json字符串
//測試前端是否能訪問
//System.out.println("getPlanePosition方法被調用了...");
PlaneService planeService = new PlaneServiceImpl();
PlanePosition planePosition = planeService.findPosition();
Gson gson = new Gson();
String jsonStr = gson.toJson(planePosition, PlanePosition.class);
//設置響應頭為json對象
response.setContentType("application/json;charset=utf-8");
//返回一個json對象
response.getWriter().print(jsonStr);
//是否能輸出正確的值
//System.out.println(jsonStr);
JSutils
之后需要用到的小工具
/**
* 獲取部署的項目地址
* @returns {string}
*/
function contextPath(){
// var curWwwPath = window.document.location.href;
var pathName = window.document.location.pathname;
// var pos = curWwwPath.indexOf(pathName);
// var localhostPaht = curWwwPath.substring(0,pos);
// var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
// return (localhostPaht + projectName);
var number = pathName.indexOf("/", 1);
return pathName.substring(0,number);
}
/**
* 生成XMLHttpRequest
* @returns {XMLHttpRequest}
*/
function ajaxFunction() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {// Internet Explorer
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
html中js代碼
模擬get方法
//全局變量
var yPosition;
function get() {
//1. 創建xmlhttprequest 對象
var request = ajaxFunction();
//2. 發送請求 用false是因為需要同步(true為異步)
request.open("GET", "PlaneServlet?method=getPlanePosition", false);
//3. 獲取響應數據 注冊監聽的意思。 一會准備的狀態發生了改變,那么就執行 = 號右邊的方法
request.onreadystatechange = function () {
//前半段表示 已經能夠正常處理。 再判斷狀態碼是否是200
if (request.readyState == 4 && request.status == 200) {
//彈出響應的信息,測試用
// alert(request.responseText);
//轉為json對象
var obj = JSON.parse(request.responseText);
//把服務器響應的json對象賦值給yPosition
yPosition = obj.yPosition;
// alert(yPosition);
}
};
request.send();
}
設置每2秒刷新一次
var myVar = setInterval(function () {
ChangePosition();
}, 2000);