Hi i am trying to call regular java class in jsp page and want to print some on jsp page when i am trying to do i am not getting any output
Here is my code
MyClass.java
package Demo;
public class MyClass {
public void testMethod(){
System.out.println("Hello");
}
}
test.jsp
<%@ page import="Demo.MyClass"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id="test" class="Demo.MyClass" />
<%
MyClass tc = new MyClass();
tc.testMethod();
%>
</body>
</html>
How can I get my desired output?
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.
Declaration tag is one of the scripting elements in JSP. This Tag is used for declare the variables. Along with this, Declaration Tag can also declare method and classes.
There are different ways to include Java code in JSP page: JSP expressions, JSP scriptlets and JSP declarations. JSP expression is used to insert a value of Java expression, converted to String, into a response returned to the client. JSP scriptlet is a container for Java code fragment in a JSP page.
Hi use your class name properly
<%
MyClass tc = new MyClass ();
tc.testMethod();
%>
instead of
<%
testClass tc = new testClass();
tc.testMethod();
%>
also when you use jsp:useBean, it creates a new object with the name as id inside your jsp converted servlet.
so use that id itself to call a method instead of creating new object again
The JSP useBean declaration is not needed in your code.
Just use
<body>
<%
MyClass tc = new MyClass();
tc.testMethod();
%>
</body>
But that WILL NOT print anything on the JSP. It will just print Hello
on the server's console.
To print Hello
on the JSP, you have to return a String from your helper java class MyClass
and then use the JSP output stream to display it.
Something like this:
In java Class
public String testMethod(){
return "Hello";
}
And then in JSP
out.print(tc.testMethod());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With