aspose file tools
The moose likes Servlets and the fly likes getServletContext() throws NullPointerException Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Servlets
Reply 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: 56179
    
  13

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


[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About 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: 251
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: 56179
    
  13

The more customary (and less error-prone) approach is to not over-ride the init(ServletConfig config) method, but rather, the init() method.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel/download
 
subject: getServletContext() throws NullPointerException
 
Similar Threads
config.getInitParameter
ServletConfig & Context ?
Servlet Context parameters query
How do you set a servlet context attribute?
Can I use web.xml in struts app for storing some param values?