java - j2ee 中没有初始上下文异常

标签 java web.xml context.xml

我正在尝试使用 context.xml 进行连接池 和web.xml

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/project_1">

<Resource auth="Container"
    driverClassName="oracle.jdbc.driver.OracleDriver"
    maxActive="100" maxIdle="30"
    maxWait="10000"
    name="connpool"
    password="oracle11"
    type="javax.sql.DataSource"
    url="jdbc:oracle:thin:@localhost:1523:system"
    username="system"/>
</Context>

web.xml

<resource-ref>
        <description>DB Connection</description>
        <res-ref-name>connpool</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

连接代码

InitialContext initialContext = new InitialContext();
Context context = (Context) initialContext.lookup("java:comp/env");
// The JDBC Data source that we just created
DataSource ds = (DataSource) context.lookup("connpool");
this.con = ds.getConnection();

异常和堆栈跟踪

Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at demo.main(demo.java:27)

C:\Users\BigGoal\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

最佳答案

Hemal ,当您在服务器上运行代码时,默认构造函数将返回上下文。当你有一个独立的程序时,默认的构造函数不会返回IC。你将不得不看看如何获​​得IC,你可能想要设置它

Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put(Context.PROVIDER_URL, "rmi://server:1099");
InitialContext context = new InitialContext(env);

此引用为Tomcat book here以及 documentation here

您可能还想在此处提及此问题 Initialcontext in a standalone Java program

希望对你有帮助!

关于java - j2ee 中没有初始上下文异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39180612/

相关文章:

java - 在 viewpager fragment 之间传递参数

java - 在 ubuntu 中检查 java 版本时权限被拒绝

java - 如何从授权中排除一个 url

Tomcat 和上下文路径

java - 在build.properties中调用类变量

java - 在嵌入式 Jetty 服务器中将 GET 参数与 POST 分开

java - web.xml 内容应该按顺序排列吗?

java - jsp web 应用程序的调试标志

java - Tomcat context.xml 文件,是否有层次结构?

eclipse - 在 Eclipse 中哪里修改 JNDI 的 xml?