I am trying to print value of a function variable in JSP Page. The function variable is located in java.class(com.project.bulk). File name is bulk.class. I tried reading the variable by writing below code in JSP file and it didn't work. Any help please?
<%@ page import="com.project.bulk.bulk" %>
<%=bulk.cellStoreVector %>
// function code is below
private static void printCellDataToConsole(Vector dataHolder) {
for (int i = 0; i < dataHolder.size(); i++) {
Vector cellStoreVector = (Vector) dataHolder.elementAt(i);
System.out.println(cellStoreVector);
for (int j = 0; j < cellStoreVector.size(); j++) {
HSSFCell myCell = (HSSFCell) cellStoreVector.elementAt(j);
String stringCellValue = myCell.toString();
// System.out.print(stringCellValue + "\t\t");
}
System.out.println();
}
}
You can't access a local variable outside that method or the block in which it is defined. The scope of local variable is confined in the block where it is defined.
Your below declaration is local to the for-loop
in which it is declared. Even in the current method, it will not be accessible outside the for-loop
. Because your loop defined a scope
of access for this variable: -
Vector cellStoreVector = (Vector) dataHolder.elementAt(i);
To access it in a JSP
outside your class
, declare that field as a private instance variable in your class. And have a public
accessor method, that will return the value of that field. Then in your JSP, you can invoke that method to get the value for a particular instance.
Remember, you need to access that method on an instance
of your class. You are accessing here directly through your class name
. If you want to access it like that, you need a static
variable.
Here's a simple example covering what all I said above: -
public class Dog {
// Private Instance variable
private int instanceVar; // Defaulted to 0
// Private Static variable
// Common for all instances
private static String name = "rohit";
// Public accessor
public int getInstanceVar() {
return this.instanceVar;
}
public void setInstanceVar(int instanceVar) {
this.instanceVar = instanceVar;
}
// Static public accessor for static variable
public static String getName() {
return name;
}
}
class Test {
public static void main(String[] args) {
// Access static method through class name
System.out.println(Dog.getName());
Dog dog = new Dog();
// Set instance variable through public accessor, on a particular instance
dog.setInstanceVar(10);
// Get instance variable value and asssign to local variable x
// x is local variable in `main`
int x = dog.getInstanceVar();
showX();
}
public static void showX() {
// x not visible here.
System.out.println(x); // Will not compile
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.