以下代码从数据库中获取用户电子邮件中的照片名称 。
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("[email protected]");
%>
它在服务器控制台上打印正确的名称 。
但如果我单靠添加 main
方法来使用此类
""https://i.sstatic.net/K63ks.png" alt="此处的内置图像描述"/"
在那级助手中,他抛出一种例外,即:
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
我使用玻璃鱼服务机和网豆来开发 。