How to call Java class in Jsp

Hi, I'm trying to call a regular java class on a jsp page and want to print some on a jsp page, when I try to do, I don't get 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 the desired result?

+4
source share
3 answers

A JSP useBean declaration in code is not required.

Just use

<body>
<%
  MyClass tc = new MyClass();
  tc.testMethod();
%>
</body>

But it will NOT print anything on the JSP. It just prints Helloto the server console. To print Helloin JSP, you need to return a String from the jper helper class MyClass, and then use the JSP output stream to display it.

Something like that:

In java class

public String testMethod(){
    return "Hello";
}

And then in JSP

out.print(tc.testMethod());
+6
source

,

<%
 MyClass tc = new MyClass ();
        tc.testMethod();

  %>

<%
 testClass tc = new testClass();
        tc.testMethod();

  %>

, jsp: useBean, id , jsp.

0

Just to fulfill all the possibilities, you can also use <% = opertator, for example:

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


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

and only for renewal, key points:

  • enable class with import tag <% @page
  • use class as usual in .java behavior
  • print data using out.print, <% = or jstl out tag
0
source

Source: https://habr.com/ru/post/1538345/


All Articles