简体   繁体   中英

getServletConfig() / getServletContext() returning null value

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().

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.

It needs to be created in the root of the WEB-INF folder. Ideally let Eclipse do this for you when you create the project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM