<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>
用的三層架構,service,dao層就不寫了,用的是C3P0鏈接池,mysql爲數據庫html
最後返回的是一個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);
以後須要用到的小工具java
/** * 獲取部署的項目地址 * @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; }
模擬get方法mysql
//全局變量 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(); }
var myVar = setInterval(function () { ChangePosition(); }, 2000);