13

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?

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
user3575501
  • 141
  • 1
  • 1
  • 7
  • 1
    System.out id the console of your web server, often redirected by the web server to a file. If you want to write to the browser, you must write to the JSP Writer. But you should NEVER use scriptlets in JSPs. Use servlets for Java code, and only use the JSP EL, the JSTL and custom tags in JSPs. Read about MVC. Read http://stackoverflow.com/questions/2188706/how-to-avoid-using-scriptlets-in-my-jsp-page – JB Nizet Apr 28 '14 at 06:01
  • whats `testClass`? It should be `MyClass` – MaVRoSCy Apr 28 '14 at 06:02

3 Answers3

11

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());
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
  • i used this showing error Message void type is not allowed here – user3575501 Apr 28 '14 at 06:16
  • probably in your java class you still have `void` as a return type in your method. Thats wrong. `Void` tells the compiler that the method is not expected to return anything. Replace `void` with `String` – MaVRoSCy Apr 28 '14 at 06:26
3

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

Karibasappa G C
  • 2,686
  • 1
  • 18
  • 27
1

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
zeppaman
  • 844
  • 8
  • 23