以下代码从给定用户电子邮件的数据库中获取照片的名称。
package NonServletFiles;
import javax.sql.*;
import java.sql.*;
import javax.naming.*;
public class GetPhotosForTheUser {
public ResultSet getData(String email) {
ResultSet set = null;
try {
String sqlQuery = "select nameofthephoto from photocaptions where useremail='" + email + "'";
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/photog"); // LINE 17
Connection connection = ds.getConnection();
PreparedStatement statement = connection.prepareStatement(sqlQuery);
set = statement.executeQuery();
while(set.next()){
System.out.println("Name Of The Photo : " + set.getString("NameOfThePhoto"));
}
}catch(Exception exc) {
exc.printStackTrace();
}
return set;
}
}
.jsp
如果我从文件中调用这个助手类:
<%
GetPhotosForTheUser gpftu = new GetPhotosForTheUser();
gpftu.getData("suhailgupta03@gmail.com");
%>
它在服务器控制台上打印正确的名称。
main
但是如果我通过添加方法单独使用这个类
在那个助手类中,它抛出一个异常,它是:
javax.naming.NamingException: Lookup failed for 'java:comp/env/jdbc/photog' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl} [Root exception is javax.naming.NamingException: Invocation exception: Got null ComponentInvocation ]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at NonServletFiles.GetPhotosForTheUser.getData(GetPhotosForTheUser.java:17)
at NonServletFiles.GetPhotosForTheUser.main(GetPhotosForTheUser.java:32)
Caused by: javax.naming.NamingException: Invocation exception: Got null ComponentInvocation
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.getComponentId(GlassfishNamingManagerImpl.java:873)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:742)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:172)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:498)
... 4 more
为什么会这样?我正在使用glassfish 服务器和 netbeans 进行此开发。