ajax請求servlet返回資料

mobclix發表於2020-10-28
function realTimeLoadValueListFunc(){
    let res=[];
    $.ajax({
        type: "get",
        url: "http://"+window.location.host+"/visual/RealTimeLoad",
        data: "",
        dataType: "text",
        async:false,
        success: function(result){
            var stringResult = result.split(',');
            res=stringResult;
        },
        error: function(){
            //alert("error");
        }
    });
    return res;
}
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.ParseException;

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 readfile.LoadAndUpdate;
import readfile.LoadHistory;

/**
 * Servlet implementation class Servlet
 */
@WebServlet("/RealTimeLoad")
public class RealTimeLoadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RealTimeLoadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		LoadAndUpdate lu=new LoadAndUpdate();
		String[] pointValuesU =lu.getPointValuesU();
     	DecimalFormat df = new DecimalFormat("#.00");
        String type = "";
        for(int i=0;i<pointValuesU.length-1;i++){
        	if(Float.parseFloat(pointValuesU[i])==0)
        		type+="0,";
			else
        		type+=df.format(Float.parseFloat(pointValuesU[i]))+',';
		}
		if(Float.parseFloat(pointValuesU[pointValuesU.length-1])==0)
			type+="0";
		else
			type+=df.format(Float.parseFloat(pointValuesU[pointValuesU.length-1]))+',';
		try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out.write(type);
            out.close();
        } catch (Exception e){
            e.printStackTrace();
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

package readfile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.magus.net.OPConnect;
import com.magus.net.OPDynamicData;

public class LoadAndUpdate {

    OPConnect conn=null;{

        try {
            //conn = new OPConnect("10.1.30.199", 8200, "sis", "openplant");
            conn = new OPConnect("10.1.21.39", 8900, "sis", "openplant");
            testUpdatePointStaticInfo();
            System.out.println("connect success!");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            // 在finally 塊中確保連線釋放會被執行
            if(conn!=null){
                try {
                    conn.close();
                } catch (IOException e) {
                    // TODO 自動生成的 catch 塊
                    e.printStackTrace();
                }
                System.out.println("connect is free!");
            }
        }
    }

    private String[] pointValuesU;

    public void testUpdatePointStaticInfo() throws IOException, Exception{
        OpenFile FpointNames = new OpenFile();
        int Flength = 0;
        String path=this.getClass().getClassLoader().getResource("/").getPath();
        String url = path+"readfile/import_daping.txt";
        File file = new File(url);
        Flength = FpointNames.FileLegth(file);
        String[] pointNamesL = FpointNames.openFile(file,Flength);

        String pointName;
        String[] pointValuesU = new String[Flength];
        String[] pointDateU = new String[Flength];
        double pointValue2;

        for(int i = 0; i < pointNamesL.length; i++) {
            pointName = pointNamesL[i];
            OPDynamicData value2 = conn.getPointDynamicData(pointName);

            if (value2 != null){
                pointValue2=value2.getAV();
                pointValuesU[i] = String.valueOf(pointValue2);
            }

            SimpleDateFormat LoadTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            pointDateU[i] = LoadTime.format(new Date());

        }
        this.pointValuesU=pointValuesU;
        //@SuppressWarnings("unused")
        //UpdateToOra U = new UpdateToOra(pointNamesL,pointValuesU,pointDateU);
    }

    public String[] getPointValuesU() {
        return this.pointValuesU;
    }

    public static void main (String args[]) throws IOException, InterruptedException{

        while(true){
            @SuppressWarnings("unused")
            LoadAndUpdate a = new LoadAndUpdate();
            Thread.sleep(50000);
        }
    }

}

//historyLoadTimeListFunc("2020-09-09 13:30:00","2020-09-09 13:31:00");
function historyLoadValueListFunc(fromTime,toTime) {
    let f=fromTime.format("yyyy-MM-dd hh:mm:ss");
    let t=toTime.format("yyyy-MM-dd hh:mm:ss");
    let res=[];
    let data={
        fromTime:f,
        toTime:t
    }
    $.ajax({
        type: "get",
        url: "http://"+window.location.host+"/visual/RealTimeLoadHistory0",
        data: data,
        dataType: "text",
        async:false,
        success: function(result){
            var tmp=result.split('&');
            var valueResult = tmp[0].split(',');
            valueResult.splice(valueResult.length-1,1);
            res= valueResult;
        },
        error: function(){
            //alert("error");
        }
    });
    return res;
}
package servlet;

import readfile.LoadAndUpdate;
import readfile.LoadHistory;

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;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Date;

/**
 * Servlet implementation class Servlet
 */
@WebServlet("/RealTimeLoadHistory0")
public class RealTimeLoadHistory0Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public RealTimeLoadHistory0Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String fromTime = request.getParameter("fromTime").trim();
		String toTime = request.getParameter("toTime").trim();
		PrintWriter out = response.getWriter();
		LoadHistory lh=new LoadHistory(fromTime,toTime);
		String[] pointHistoryValuesU0=lh.getPointHistoryValuesU();
		String[] pointHistoryTimesU0=lh.getPointHistoryTimesU();
		String type= "";



		DecimalFormat df = new DecimalFormat("#.00");
		for(int i=0;i<pointHistoryValuesU0.length;i++){
			type=type+""+df.format(Float.parseFloat(pointHistoryValuesU0[i]))+',';
		}
		type=type+'&';
		for(int i=0;i<pointHistoryTimesU0.length;i++){
			type=type+pointHistoryTimesU0[i]+",";
		}
		try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out.write(type);
            out.close();
        } catch (Exception e){
            e.printStackTrace();
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

package readfile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import com.magus.net.OPConnect;
import com.magus.net.OPHisData;

public class LoadHistory {

    public String[] getPointHistoryValuesU() {
        return pointHistoryValuesU;
    }

    private String[] pointHistoryValuesU;

    public String[] getPointHistoryTimesU() {
        return pointHistoryTimesU;
    }

    private String[] pointHistoryTimesU;

    private OPConnect conn=null;

    public LoadHistory(String f,String t) {
        try {
            //conn = new OPConnect("10.1.30.199", 8200, "sis", "openplant");
            conn = new OPConnect("10.1.21.39", 8900, "sis", "openplant");
            testgetPointHistorys(f, t);
            System.out.println("connect success!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 在finally 塊中確保連線釋放會被執行
            if (conn != null) {
                try {
                    conn.close();
                } catch (IOException e) {
                    // TODO 自動生成的 catch 塊
                    e.printStackTrace();
                }
                System.out.println("connect is free!");
            }
        }
    }

    public void testgetPointHistorys(String fromTime,String toTime) throws ParseException, IOException{
        OpenFile FpointNames = new OpenFile();
        int Flength = 0;
        String path=this.getClass().getClassLoader().getResource("/").getPath();
        String url = path+"readfile/import_daping.txt";
        File file = new File(url);
        Flength = FpointNames.FileLegth(file);
        String[] pointNames = FpointNames.openFile(file,Flength);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//注意月份是MM
        Date from = simpleDateFormat.parse(fromTime);
        Date to = simpleDateFormat.parse(toTime);
        //Date to = new Date();
        //Calendar calendar= Calendar.getInstance();
        //calendar.add(Calendar.MINUTE, -1);
        //Date from=calendar.getTime();

        Map<String, OPHisData[]> map= conn.getPointHistorys(pointNames,from,to, 1,1);

        //for (int i = 0; i < pointNames.length; i++) {
        for (int i = 0; i < 1; i++) {
            OPHisData[] ophs = map.get(pointNames[i]);
            String[] pointValuesU = new String[ophs.length];
            String[] pointTimesU= new String[ophs.length];
            for (int j = 0; j < ophs.length; j++) {
                //System.out.println(ophs[j]);
                pointValuesU[j]=ophs[j].getAV()+"";
                Date d =new Date(ophs[j].getTime());
                pointTimesU[j]=d.toString();
            }
            this.pointHistoryValuesU=pointValuesU;
            this.pointHistoryTimesU=pointTimesU;
        }
    }


    /*public static void main (String args[]) throws IOException, InterruptedException{

        while(true){
            @SuppressWarnings("unused")
            LoadHistory a = new LoadHistory();
            Thread.sleep(50000);
        }
    }*/

}

package readfile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;



public class OpenFile {
	
	@SuppressWarnings({ "resource" })
	public int FileLegth(File file)
	{
		File saveFile = file;
		int Flegth = 0;
	
	        try {

	        	int count = 0;
	        	
		        FileReader fileReader = new FileReader(saveFile);
		        BufferedReader buf = new BufferedReader(fileReader);
		        
				String value = buf.readLine();
				if(value != null)
				while(value !=null){
				count++;
				value = buf.readLine();
				//System.out.println(value);
				}
				Flegth = count;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

		return Flegth;
		
	}
	
	@SuppressWarnings({ "resource", "unused" })
	public String[] openFile(File file,int Flength)
	{
		File saveFile = file;
		int num = Flength;
		String[] myArray = new String[num];//100:這個值你自己定義,但不宜過大,要根據你檔案的大小了,或者檔案的行數
	
    try {


        FileReader fileReader = new FileReader(saveFile);
        BufferedReader buf = new BufferedReader(fileReader);
        
        int i = 0;
        String bufToString = "";
        String readLine = "";
        while((readLine = buf.readLine()) != null){
            myArray[i] = readLine;
            //String a1 = null;
            //a1 = myArray[i];
            i++;
            //System.out.println(a1);
        }
   }
    catch (Exception e) {
        e.printStackTrace();
    }
    return myArray;
    

}

}

相關文章