3

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");
David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
display4
  • 71
  • 1
  • 1
  • 7
  • Where is this code in your servlet? Is it in ctor? You will get config only in methods which are inherited from `HttpServlet`: `init, doGet`, etc. – Victor Sorokin Oct 21 '14 at 22:16
  • 2
    just because it extends from HttpServlet it does not mean it's a servlet being started and managed by the container. Can you post the whole servlet code? – Leo Oct 21 '14 at 22:16

2 Answers2

23

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

Mahsa2
  • 412
  • 6
  • 15
user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thank you for the suggestion. I am accessing the ServletContext in a plain java class which is a non-web component i.e. the final layer of the application. There is not front end for the application. Any thoughts on how I can access ServletContext without the web layer? – display4 Oct 21 '14 at 23:31
  • You can't. A `Servlet` only runs in a servlet container. – user207421 Oct 21 '14 at 23:36
  • @EJP: Did you mean `init(ServletConfig config)` instead of `ServletContex contextt`? The document @EJP mentioned can be found [here](https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/GenericServlet.html#init%28javax.servlet.ServletConfig%29). – Mahsa2 Mar 04 '16 at 22:58
  • @MahsaMohammadkhani Thank you, yes. – user207421 Mar 04 '16 at 23:12
  • This young player was trapped! Thank you – Pedro García Medina May 28 '20 at 02:21
0

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.

lico_w999
  • 11
  • 2
  • You didn't get a null `ServletContext` because you had a file in the wrong place. You are describing a different problem. – user207421 Jun 08 '18 at 17:34