user3575501
user3575501

Reputation: 151

How to call Java class in Jsp

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?

Upvotes: 14

Views: 95408

Answers (3)

zeppaman
zeppaman

Reputation: 854

Just to complete all the opportunities, You could also use the <%= opertator like:

<%
 MyClass tc = new MyClass ();
%>


<h1><%= tc.testMethod();  %> </h1>

and just for resume, the key points:

  1. include class with <%@ page import tag
  2. use the class as usual in .java behaviour
  3. print data with out.print, <%= or jstl out tag

Upvotes: 1

Karibasappa G C
Karibasappa G C

Reputation: 2732

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

Upvotes: 3

MaVRoSCy
MaVRoSCy

Reputation: 17839

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());

Upvotes: 11

Related Questions