How to Call a Java Class in JSP

In this post, we will show you how to call a Java class from JSP.
Now, in the previous article, I mentioned that you wanted to minimize the scriptlets and declarations in a JSP.
You wanna avoid dumping thousands of lines of code in your JSP. Now, it's okay to add small bits of script, small bits of declarations, but don't overdo it.
So, in order to kinda help with this problem, you can refactor your code into a separate Java class or make use of MVC.
So the Java class will have all of our code, all of our business logic, and so on, and the JSP can simply make a call, let the Java code or the Java class do the heavy lifting, and then the JSP can get the results and continue on with its processing.

Development Steps

  1. Create a Java class
  2. Create a JSP page
  3. Call Java methods from Java class into JSP page.

1. Create a Java class - Calculator.java

I assume that you have already JSP application. Now you can create a Java class named Calculator.java and keep following code into it:
package net.javaguides.jsp.tutorial;

public class Calculator {
    public int addition(int num1, int num2) {
        return (num1 + num2);
    }

    public int substraction(int num1, int num2) {
        return (num1 - num2);
    }

    public int multiplication(int num1, int num2) {
        return (num1 * num2);
    }

    public int division(int num1, int num2) {
        return (num1 / num2);
    }
}

Create a JSP page - calculator.jsp

Let's create a calculator.jsp file and add the following code to it.
Let's import Calculator Java class and use its methods:
<%@page import="net.javaguides.jsp.tutorial.Calculator"%>
Here is a complete example which is calling Calculator Java class methods and displaying results on brower.
<%@page import="net.javaguides.jsp.tutorial.Calculator"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <% Calculator calculator = new Calculator(); %>

    Addition of 20 + 10 =
    <%= calculator.addition(20, 10) %>

    <br><br> Subtraction of 20 - 10 =
    <%= calculator.substraction(20, 10) %>

    <br><br> Multiplication of 20 * 10 =
    <%= calculator.multiplication(20, 10) %>

    <br><br> Division of 20/10 =
    <%= calculator.division(20, 10) %>

</body>
</html>
Let's invoke this JSP page from a Web browser, you see the table on a browser:

In the next article, we will learn JSP Actions - useBean, setProperty and getProperty


Comments