Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Java class in Jsp

Tags:

java

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?

like image 241
user3575501 Avatar asked Apr 28 '14 05:04

user3575501


People also ask

Can we call a java class from JSP?

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.

Can we declare class in JSP?

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.

What are the different methods to call Java code from JSP page?

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.


2 Answers

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

like image 151
Karibasappa G C Avatar answered Sep 19 '22 14:09

Karibasappa G C


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());
like image 45
MaVRoSCy Avatar answered Sep 20 '22 14:09

MaVRoSCy