简体   繁体   English

从jsp调用Java类

[英]call java class from jsp

<%@ page language="java" import="DBConnect"%>


<%
try
{
System.out.println("\n--------------------");
System.out.println("\n loading ..");

DBConnect.connectToDb();

%>

<h3>Connection ok</h3>
<%
}
catch(Exception e)
{
e.printStackTrace();
}
%>

gives me following error how to load java class in jsp 给我以下错误如何在jsp中加载Java类

org.apache.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 12 in the generated java file
The import DBConnect cannot be resolved

An error occurred at line: 16 in the jsp file: /applicationservices/fileshare/vm/TestJdbc.jsp
DBConnect cannot be resolved
13: System.out.println("\n--------------------");
14: System.out.println("\n loading ..");
15: 
16: DBConnect.connectToDb();
17: 
18: %>
19: 

You need to create a package for the application which would be something like 您需要为应用程序创建一个程序包,类似于

com.yourappname.data

then create your DBConenct class in that package or refactor it in there so that when you need to import the class you do so by using 然后在该程序包中创建DBConenct类或在其中重构它,以便在需要导入该类时使用

import com.yourappname.data.DBConnect

The you can import and use the class in your jsp 您可以在jsp中导入和使用该类

<%@page import="com.yourappname.data.DBConnect"%>

On a side note, you shouldn't be doing any database acces within the jsp you should instead be doing all of your data access within a servlet. 附带说明一下,您不应在jsp中进行任何数据库访问,而应在servlet中进行所有数据访问。

Add the package prefix to DBConnect: 将包前缀添加到DBConnect:

<%@ page language="java" import="full.package.path.DBConnect"%>

Where full.package.path is the actual package of DBConnect . 其中full.package.pathDBConnect的实际包。

类应该是公共的,方法也应该声明为公共

You page has no error. 您的页面没有错误。 Please clean and build your project again and retest it.Putting your class in some package is good practice but without using this is no problem for test project. 请清理并再次构建您的项目,然后重新测试。将您的类放入某个包中是一种很好的做法,但是不使用它对于测试项目来说没有问题。

Make sure you see 确保你看到

DBConnect.class

in your 在你的

WEB-INF/classes

directory. 目录。 If it's not there, the class isn't on your classpath if you are running in tomcat or similar. 如果不存在,则如果您在tomcat或类似环境中运行,则该类不在您的类路径中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM