Get data from a Java class in a JSP page

Home > Search
  by

class is a collection of markup that performs a certain function. 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.

Let's say you've created a class called People.java (in Eclipse in this example). 

 

In this example, the People.java class is in the com.sample.main package. There is a public class called "People", and a variable called "name" is created with a value of "John Doe".  The "name" variable is returned, so that it can be used (such as in a JSP page). In other words, this class will display the text "John Doe".

package com.sample.main;

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

  public String getName(){
    return name;
  }

}

 

This variation produces the same exact result.

package com.sample.main;

public class People {
  public String name;

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

  public String getName(){
    return name;
  }

}

 

The class is now ready to be used. For example, in the <head> of a JSP page, you would import the People class.

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

 

In the <body> of the JSP page, create a new people object (foo in this example). The text "People" must match the name of the class being imported. Using foo, get the value of the name variable. Be careful to use "out.print" and not "out.println". 

<%
  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