【问题标题】:Attempting to access web.xml getting NoInitialContextException尝试访问 web.xml 得到 NoInitialContextException
【发布时间】:2016-02-08 15:39:46
【问题描述】:

我正在为班级构建一个 Web 应用程序(是的,这是一项家庭作业)。我正在使用 Eclipse 和 Tomcat 8。我有以下服务工厂代码:

package com.OrderOnline.model.service.factory;


import javax.naming.Context;
import javax.naming.InitialContext;

import com.OrderOnline.model.service.interfaces.IService;

public class ServiceFactory
{
    public IService getService(String name) throws Exception
    {
        try
        {
            Class<?> newClass = Class.forName(getImplName(name));
            return (IService)newClass.newInstance();
        }
        catch(Exception e)
        {
            throw new Exception(name);
        }
    }

    private String getImplName(String name) throws Exception
    {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");

        String lookupClass = (String) envCtx.lookup(name);
        return lookupClass;
    }
}

我希望这会在我位于 OrderOnline/WebContent/WEB-INF/web.xml 的 web.xml 文件中查看以下内容:

  <env-entry>
    <env-entry-name>IUserSvc</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>com.OrderOnline.model.service.interfaces.IUserSvc</env-entry-value>
  </env-entry>

相反,我在运行此行时抛出异常:

Context envCtx = (Context) initCtx.lookup("java:comp/env");

例外是:

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

我对此很陌生,所以我可能会遗漏一些重要的信息来帮助我,我很乐意提供更多需要的信息。感谢任何可以帮助我从 web.xml 文件中读取 env-entry-value 的帮助。

【问题讨论】:

    标签: java eclipse tomcat8


    【解决方案1】:

    您需要一个初始上下文工厂,如 SO 上的 this answer 中所述。

        System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                  "org.apache.naming.java.javaURLContextFactory");
    

    【讨论】:

    • 根据 Tomcat 文档,会自动提供初始上下文。我的初始上下文代码看起来与他们在此处提供的几乎相同:tomcat.apache.org/tomcat-8.0-doc/jndi-resources-howto.html。话虽这么说,我尝试了你所指出的,但这也行不通。这个很奇怪,因为我似乎无法捕捉到异常。我将 getImplName() 的内容放在 try/catch 中,当它遇到 Context envCtx 代码时,它的行为就像遇到了 return 语句。没有抛出异常,它只是退出类。我得在上午看更多
    猜你喜欢
    • 2016-05-22
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2018-08-10
    • 2014-02-10
    • 2019-08-16
    相关资源
    最近更新 更多