Reputation: 41
Hello I still have a problem, I can't display any data in jsp page, as you can see in the code i have imported the java class into jsp and created an object of the class and called the method for output from java class but it seems something wrong ..help please. (please explain your advice because some hint are harder to understand - thanks)
package mydata;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
public class test {
public test() {
Sigar sigar = new Sigar();
String output = " ";
CpuInfo[] cpuInfoList = null;
try {
cpuInfoList = sigar.getCpuInfoList();
} catch (SigarException e) {
e.printStackTrace();
return;
}
for (CpuInfo info : cpuInfoList) {
output += "\nCPU\n";
output += "Vendor: " + info.getVendor() + "\n";
output += "Clock: " + info.getMhz() + "Mhz\n";
output += "Core: " + info.getCoresPerSocket();
}
System.out.println(output);
}
public static void main(String[] args) {
test main = new test();
}
}
//JSP Code
<%@page import="mydata.test"%>
<%@page import="org.hyperic.sigar.Sigar"%>
<%@page import="org.hyperic.sigar.CpuInfo"%>
<%@page import="org.hyperic.sigar.SigarException"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Welcome to data page</h1>
<%@ page import="mydata.test.*"%>
<%
String output="";
CpuInfo[] cpuInfoList = null;
test ts = new test();
Sigar sigar = new Sigar();
out.println(output);
out.println(sigar.getCpuInfoList());
%>
</body>
</html>
Upvotes: 0
Views: 4238
Reputation: 1622
The output stream used in a servlet, to output the content is different than standard output stream (out != System.out).
There are two ways to solve your problem:
Pass the output stream object to your test method in your class:
test(OutputStream out) {
...
out.println(output);
}
Return your output from test method:
StringBuilder buffer = new StringBuilder();
for (...) {
buffer.append(...);
}
return buffer.toString();
I suggest using StringBuilder instead of concatenating the String objects since this can significantly affect performance.
Upvotes: 0
Reputation: 601
You need to declare your output variable in class scope and add a getter method to return it.
Then, after invoking the constructor of test class, use the getter method to retrieve the output string.
For example:
// Java
public class test {
private String output;
public String getOutput() {
return this.output;
}
// JSP
<%
test ts = new test();
out.println(ts.getOutput());
%>
Upvotes: 1