• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

getServletContext() throws NullPointerException

 
Ali Ekber
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have below code in a servlet. I believe getServletContext() is throwing NullPointerException.

RequestDispatcher rd = getServletContext().getRequestDispatcher("/ialist.jsp");

I initiliazed the servlet context in the deployment descriptor (I think!). Here is the code:

...
<context-param>
<param-name>none</param-name>
<param-value>none</param-value>
</context-param>
...

Anyone know how to get the servlet context without getServletContext() throwing exception. Thx.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64620
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rather than guessing, why don't you put in some diagnostic statements to show whether getServletContext() is indeed returning null or not.

Btw, where in your servlet does this statement appear?

Also, you do not need to do anything in your web.xml to "initiliaze the servlet context". The context-param element you posted does nothing except establish a context parameter with the name of "none".
 
Ali Ekber
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is at the end of the doPost, where I am finished and returning it. I am sure the exception is caused by getServletContext(), since when I replace it by request, the exception disappears.
 
Kerry Wilson
Ranch Hand
Posts: 254
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe there is an error in the way the path is written to the jsp and it is returning a null dispatcher, or the getRequestDispatcher method is throwing a null pointer. Could you post a stack trace?
 
Ali Ekber
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I solved the problem. I needed to initialize the servlet context object in the init method.

.....
private ServletContext ctx = null;
public void init(ServletConfig config) throws ServletException {
super.init(config);
ctx = config.getServletContext();
}
....
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64620
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The more customary (and less error-prone) approach is to not over-ride the init(ServletConfig config) method, but rather, the init() method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic