gpt4 book ai didi

java - 在jsp页面中调用Java类

转载 作者:行者123 更新时间:2023-12-02 04:44:03 24 4
gpt4 key购买 nike

我需要你们的帮助,我有这个 JAVA 类,它允许监视来自中央处理器单元 (CPU) 的数据,我需要调用或将 Java 类的输出显示到 JSP 或 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();
}

}

最佳答案

从 JSP 调用 Java 代码的方法有很多种:

首先:从 Scriptlet 调用方法(不是好方法):

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

第二:在请求中设置对象并在JSP上获取对象,如下所示:

在 Servlet 中:

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

在你的JSP.jsp中:

${yourData}

第三:使用page指令在JSP上导入类并实例化并调用方法,如下:

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

关于java - 在jsp页面中调用Java类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29844245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com