2015-04-24 82 views
0

我需要你的幫助傢伙我有這個JAVA類允許監視來自中央處理器單元(CPU)的數據,我需要調用或顯示從Java類輸出到JSP或SERVLET網頁頁。在jsp頁面調用Java類

 package cpudata; 

     import java.math.BigInteger; 
     import java.util.Random; 
     import org.hyperic.sigar.CpuInfo; 
     import org.hyperic.sigar.CpuPerc; 
     import org.hyperic.sigar.ProcCpu; 
     import org.hyperic.sigar.Sigar; 
     import org.hyperic.sigar.SigarException; 

     /** 
      * 
      * @author alsadig 
      */ 
     public class CpuData { 

      private static Sigar sigar; 

      public CpuData(Sigar s) throws SigarException { 
       sigar = s; 
       System.out.println(cpuInfo()); 
      } 

      public static void main(String[] args) throws InterruptedException, SigarException { 
       new CpuData(new Sigar()); 
       CpuData.startMetricTest(); 
      } 
      private static void startMetricTest() throws InterruptedException, SigarException { 
       new Thread() { 
        public void run() { 
         while(true) 
         BigInteger.probablePrime(MAX_PRIORITY, new Random()); 
        }; 
       }.start(); 
       while(true) { 
        String pid = ""+sigar.getPid(); 
        System.out.print(getMetric(pid)); 
        for(Double d:getMetric()){ 
         System.out.print("\t"+d); 
        } 
        System.out.println(); 
        Thread.sleep(1000); 
       }  
      } 

      public String cpuInfo() throws SigarException { 
       CpuInfo[] infos = sigar.getCpuInfoList(); 
       CpuInfo info = infos[0]; 

       String infoString = info.toString(); 
       if ((info.getTotalCores() != info.getTotalSockets()) 
         || (info.getCoresPerSocket() > info.getTotalCores())) { 
        infoString+=" Physical CPUs: " + info.getTotalSockets(); 
        infoString+=" Cores per CPU: " + info.getCoresPerSocket(); 
       } 

       long cacheSize = info.getCacheSize(); 
       if (cacheSize != Sigar.FIELD_NOTIMPL) { 
        infoString+="Cache size...." + cacheSize; 
       } 
       return infoString; 
      } 

      public static Double[] getMetric() throws SigarException { 
       CpuPerc cpu = sigar.getCpuPerc(); 
       double system = cpu.getSys(); 
       double user = cpu.getUser(); 
       double idle = cpu.getIdle(); 
       return new Double[] {system, user, idle}; 
      } 

      public static double getMetric(String pid) throws SigarException { 
       ProcCpu cpu = sigar.getProcCpu(pid); 
       return cpu.getPercent(); 
      } 

     } 
+0

您可以創建對象並調用此類的適當方法。 – yogesh

回答

2

有很多方法從JSP調用Java代碼:

第一:從Scriptlet中調用方法,(不是好辦法):

<%= com.example.MyUtility.getSomething() %> 

二:在請求中設置對象並在JSP上獲取對象,如下所示:

在Servlet的:

request.setAttribute("yourData", MyUtility.methodToCall()) 
RequestDispatcher dispatcher = request.getRequestDispatcher("yourJSP.jsp"); 
dispatcher.forward(request, response); 

在yourJSP.jsp:

${yourData} 

三:使用頁面指令和實例,並調用該方法導入的JSP類,如下:

<%@page import="com.example.MyUtility"%> 
<% 
    MyUtility obj = new MyUtility(); 
    obj.methodToCall(); 
%>