[英]getServletConfig() / getServletContext() returning null value
I want to get servletContext
in a Java class to read a file from WEB-INF
directory. 我想在Java类中获取
servletContext
以从WEB-INF
目录中读取文件。 I extended my class with HttpServlet
and tried to get the context as in the below code, but the servlet config is returned as null. 我使用
HttpServlet
扩展了我的类,并尝试获取上面的代码中的上下文,但servlet配置返回null。 I don't use any jsp or controller. 我不使用任何jsp或控制器。 My intention is to read a file directly placed in the
WEB-INF
directory from a Java class. 我的目的是从Java类中读取直接放在
WEB-INF
目录中的文件。 Please let me know how I can get not null servletConfig
/ servletContext
in the class: 请让我知道如何在类中得到null
servletConfig
/ servletContext
:
ServletConfig config = getServletConfig();
ServletContext context = config.getServletContext();
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/samplefile");
Trap for young players. 陷阱为年轻球员。 If you override the
如果你覆盖了
public void init(ServletConfig config)
method, you must call 方法,你必须打电话
super.init(config);
inside the method. 在方法内部。 Otherwise the superclass sees the context as
null.
否则,超类将上下文视为
null.
It's mentioned in the Javadoc: 它在Javadoc中提到:
When overriding this form of the method, call
super.init(config).
覆盖此方法的形式时,请调用
super.init(config).
NB You can get the context directly via getServletContext().
注意您可以通过
getServletContext().
直接获取上下文getServletContext().
There's no need to go via getServletConfig().
没有必要通过
getServletConfig().
I had this same issue and it turned out the web.xml file was created in the wrong place and was not being loaded by the container. 我有同样的问题,结果发现web.xml文件是在错误的地方创建的,并没有被容器加载。
It needs to be created in the root of the WEB-INF folder. 它需要在WEB-INF文件夹的根目录中创建。 Ideally let Eclipse do this for you when you create the project.
理想情况下,Eclipse会在您创建项目时为您执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.