How to Call a Java Class in JSP

In this post, we will show you how to call a Java class from a JSP page.

In the previous articles, we mentioned the importance of minimizing the use of scriptlets and declarations in a JSP. It's advisable to avoid embedding extensive Java code directly in your JSP pages. Instead, you should encapsulate business logic in separate Java classes, allowing your JSP to focus on presentation.

Development Steps

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

1. Create a Java class - Calculator.java

Assume you already have a JSP application set up. Now, create a Java class named Calculator.java and add the following code:

package net.javaguides.jsp.tutorial;

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

    public int subtraction(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);
    }
}

2. Create a JSP page - calculator.jsp

Next, create a calculator.jsp file and add the following code to it. This JSP page will import the Calculator class and use its methods:

<%@ 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>Calculator Example</title>
</head>
<body>

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

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

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

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

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

</body>
</html>

In this example, the JSP page imports the Calculator class and creates an instance of it. The methods of the Calculator class are called to perform various arithmetic operations, and the results are displayed on the web page.

Result

When you invoke this JSP page from a web browser, you will see the following output:

Calculator Example Output

Conclusion

Refactoring business logic into separate Java classes and calling these classes from JSP pages helps keep your JSP code clean and maintainable. This approach leverages the strengths of both Java and JSP, making your web application more modular and easier to manage.

Comments