Calling a Java class from a JSP involves using JavaBeans or servlets to encapsulate the business logic and then accessing the JavaBean's methods or servlet's functionalities within the JSP page. Here are the steps to do it:
package com.example;
public class GreetingBean {
public String generateGreeting(String name) {
return "Hello, " + name + "!";
}
}
<%@ page import="com.example.GreetingBean" %>
<%
GreetingBean greetingBean = new GreetingBean();
%>
<!DOCTYPE html>
<html>
<head>
<title>Calling Java Class from JSP</title>
</head>
<body>
<h1>Greeting Example</h1>
<% String name = "John"; %>
<p><%= greetingBean.generateGreeting(name) %></p>
</body>
</html>
In this example, we are using the generateGreeting() method of the GreetingBean class to display a personalized greeting on the web page.
Note: The above example demonstrates a simple way to call a Java class from a JSP using scriptlets. However, using scriptlets is not recommended for complex applications. Instead, consider using JSTL, Expression Language (EL), or custom tags to handle dynamic content and logic in a more maintainable and organized manner. Additionally, it's a good practice to use the MVC (Model-View-Controller) design pattern, where JavaBeans or servlets act as the Model, JSP as the View, and a controller (such as a servlet) handles the flow of data between the Model and the View.