我需要你的帮助我有这个JAVA类允许监控来自中央处理器单元(CPU)的数据,我需要调用或显示Java类的输出到JSP OR SERVLET网页。
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 :(得分: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}
第三:使用page指令在JSP上导入类并实例化它并调用方法,如下所示:
<%@page import="com.example.MyUtility"%>
<%
MyUtility obj = new MyUtility ();
obj.methodToCall();
%>