如何在Jsp中调用Java类 [英] How to call Java class in Jsp

查看:356
本文介绍了如何在Jsp中调用Java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在尝试在jsp页面中调用常规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

这是我的代码

MyClass.java

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>

如何获得所需的输出?

推荐答案

您的代码中不需要JSP useBean声明。

The JSP useBean declaration is not needed in your code.

只需使用

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

但这不会在JSP上打印任何内容。它只会在服务器的控制台上打印 Hello
要在JSP上打印 Hello ,您必须从帮助程序java类 MyClass 返回一个String,并且然后使用JSP输出流来显示它。

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.

这样的事情:

在java类中

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

然后在JSP中

out.print(tc.testMethod());

这篇关于如何在Jsp中调用Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆