FreeKB - Importing a Java class or bean into a JSP page
Importing a Java class or bean into a JSP page

Home > Search


This assumes you have created a class or bean that contains a method.

If the class or bean that you want to use exists in the same application as your JSP page, there is no need to import the JAR that contains the bean/class into your application. On the other hand, if the bean/class was created in some other app and then exported into a JAR file, you will need to add the JAR file that contains the bean/class into your Java Build Path.

Let's use this as an example.

package com.sample.main;

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

  public String myMethod(){
    return name;
  }
}

 

In the <head> of your JSP page, import the bean/class. In this example, "MyClass" in the "com.sample.main" package is imported.

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

 

In the <body> of the JSP page, create a new object (foo in this example). In this example, "MyClass" is used because the object must have the same name as the bean/class being imported.

Then, call the method you want to use (myMethod in this example). Be careful to use "out.print" and not "out.println". This will do whatever myMethod is configured to do, which in this example, would print "John Doe".

<%
  MyClass foo = new MyClass();
  out.print(foo.myMethod());
%>

 

Navagiating to the JSP page should now display John Doe.

 

Let's consider this class.

package com.sample.main;

public class MyClass {

  // create myMethod
  private void myMethod() {
    System.out.println("John Doe");
  }            

  // make myMethod accessible in a JSP page
  public static void main(String[] args) {
    MyClass foo = new MyClass();
    foo.myMethod();              
  }

}

 

In the <body> of the JSP page, call myMethod.

<%
  MyClass foo = new MyClass();
  foo.myMethod();
%>

 

Unlike the prior example, nothing will be printed on the JSP page. This is because the class uses "system.out.println". In this case, "John Doe" would be appended to the application servers log file.



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 5174e in the box below so that we can be sure you are a human.




Comments