Get data from a Java class in a JSP page

Home > Search
  by

class is a collection of objects that can be used. To use an analogy, the military has a class of officers classifed as privates, and a different class of officers classified as admirals. When combat is needed, the officers from the privates class will be used. When negotiation is needed, the officers from the admirals class will be used. In the same way, when a Java programs needs to use certain objects, the class that contains the objects will be used.

Take for example the following class. In this example, there is a public class called "People". A variable called "name" is created with a value of "John Doe".  The "name" variable is returned, so that it can be used in a JSP page.

public class People {
  public String name = "John Doe";

  public String getName(){
    return name;
  }

}

 

This variation produces the same exact result.

public class People {
  public String name;

  public People() {
    name = "John Doe";
  }

  public String getName(){
    return name;
  }

}

 

In the <head> of your JSP page, import the People class.

<%@page import="com.main.servlet.People"%>

 

In the <body> of your JSP page, create a new people object (foo in this example), and then using foo, get the value of the name variable.

<%
  People foo = new People();
  out.print(foo.getName());
%>

 

Navagiating to the JSP page should now display John Doe.

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments