简体   繁体   中英

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

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

import com.yourappname.data.DBConnect

The you can import and use the class in your 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.

Add the package prefix to DBConnect:

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

Where full.package.path is the actual package of DBConnect .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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