I want to get servletContext
in a Java class to read a file from WEB-INF
directory. 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. I don't use any jsp or controller. My intention is to read a file directly placed in the WEB-INF
directory from a Java class. Please let me know how I can get not null servletConfig
/ servletContext
in the class:
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.
It's mentioned in the Javadoc:
When overriding this form of the method, call
super.init(config).
NB You can get the context directly via getServletContext().
There's no need to go via getServletConfig().