aspose file tools*
The moose likes Servlets and the fly likes getServletContext() throws NullPointerException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "getServletContext() throws NullPointerException" Watch "getServletContext() throws NullPointerException" New topic
Author

getServletContext() throws NullPointerException

Ali Ekber
Ranch Hand

Joined: Jun 12, 2005
Posts: 41
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

Joined: Jan 10, 2002
Posts: 61648
    
  67

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".


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Ali Ekber
Ranch Hand

Joined: Jun 12, 2005
Posts: 41
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

Joined: Oct 29, 2003
Posts: 254
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?


http://www.goodercode.com
SCJP 1.4
Ali Ekber
Ranch Hand

Joined: Jun 12, 2005
Posts: 41
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

Joined: Jan 10, 2002
Posts: 61648
    
  67

The more customary (and less error-prone) approach is to not over-ride the init(ServletConfig config) method, but rather, the init() method.
 
 
subject: getServletContext() throws NullPointerException