Bright Java Tutorial

is brought to you by DoITBright LLC

JSP

Import My Java Class In My JSP

In this lesson, we will learn how to use the Java class we wrote ourselves inside our JSP. For example, you wrote a utility class that adds 2 numbers and returns the value. For sure there is a way to do this purely using JSP technology but based on my industry experience, it is highly recommended to put this kind of logic in a utility class. I wont discuss any further the reason for the before mentioned statement because it is out of the scope for this lesson. In your 'jspLesson' directory, create a directory and name it as 'WEB-INF'. Inside that new directory, create a directory and name it as 'classes'. Then, inside that 'classes' directory, create a directory and name it as 'pkg'. Inside that 'pkg' directory, create a Java class file and name it as 'ExampleUtility.java'. Here is the content of that file...

  package pkg;
  
  public class ExampleUtility {

    public double addTwoNumbers(double num1, double num2) {
      return num1 + num2;
    }
  }
                            

Here is what you might have right now on your Windows OS directory and file structure... 'c:\BrightJavaTutorial\workspace\jspLessons\WEB-INF\classes\pkg\ExampleUtility.java' Go to that directory. Then compile the Java file by executing the javac command like this...

  javac ExampleUtility.java
                            

It should compile successfully. Once the class file is generated, go to the 'c:\BrightJavaTutorial\workspace\jspLessons' directory. Create a file and name it as 'importMyClassInMyJsp.jsp'. Here is the content of that JSP file...

  <%@ page import="pkg.ExampleUtility" %>
  <html>
    <head>
      <title>Import My Java Class In My JSP</title>
    </head>
    <body>
  <%
    ExampleUtility util = new ExampleUtility();
    double sum = util.addTwoNumbers(12.5, 3.1);
    out.println("sum = " + sum);
  %>
    </body>
  </html>
                            

Deploy the jspLessons application in your tomcat webapps directory and start the server. Take a look at your accomplishment. Imagine the endless possibilities that opened to you right now.


Back    Next