我想在Java类中获得servletContext
,以便从WEB-INF
目录中读取文件。我用HttpServlet
扩展了我的类,并试图获得下面代码中的上下文,但servlet配置返回为null。我不使用任何jsp或控制器。我的意图是从Java类中读取一个直接放在WEB-INF
目录中的文件。请让我知道如何在类中获得不为空的servletConfig
/servletContext
ServletConfig config = getServletConfig();
ServletContext context = config.getServletContext();
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/samplefile");
年轻玩家的陷阱。如果您覆盖
public void init(ServletConfig config)
方法,必须调用
super.init(config);
方法内部。否则,超类将上下文视为null.
。它在Javadoc:中提到
重写此形式的方法时,请调用
super.init(config).
注意:您可以直接通过getServletContext().
获取上下文。无需通过getServletConfig().
我遇到了同样的问题,结果发现web.xml文件创建在错误的位置,容器没有加载它。
它需要在WEB-INF文件夹的根目录中创建。理想情况下,当您创建项目时,让Eclipse为您完成这项工作。