如何在 Jsp 中调用 Java 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23333488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call Java class in Jsp
提问by user3575501
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
嗨,我正在尝试在 jsp 页面中调用常规 java 类,并想在尝试时在 jsp 页面上打印一些我没有得到任何输出
Here is my code
这是我的代码
MyClass.java
我的类
package Demo;
public class MyClass {
public void testMethod(){
System.out.println("Hello");
}
}
test.jsp
测试.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?
我怎样才能得到我想要的输出?
采纳答案by MaVRoSCy
The JSP useBean declaration is not needed in your code.
您的代码中不需要 JSP useBean 声明。
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.
但这不会在 JSP 上打印任何内容。它只会Hello
在服务器的控制台上打印。要Hello
在 JSP 上打印,您必须从帮助程序 java 类返回一个字符串MyClass
,然后使用 JSP 输出流来显示它。
Something like this:
像这样的东西:
In java Class
在 Java 类中
public String testMethod(){
return "Hello";
}
And then in JSP
然后在 JSP 中
out.print(tc.testMethod());
回答by Karibasappa G C
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.
同样,当您使用 jsp:useBean 时,它会在您的 jsp 转换后的 servlet 中创建一个名称为 id 的新对象。
so use that id itself to call a method instead of creating new object again
所以使用该 id 本身来调用一个方法而不是再次创建新对象
回答by zeppaman
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:
就简历而言,关键点:
- include class with <%@ page import tag
- use the class as usual in .java behaviour
- print data with out.print, <%= or jstl out tag
- 包含带有 <%@ 页面导入标签的类
- 在 .java 行为中照常使用该类
- 使用 out.print、<%= 或 jstl out 标签打印数据