• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

not able to get ContextPath(); getting null pointer exception

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is the statement I have in my JSP

<%SampleClass sample= new SampleClass(); %>

Here is part of my SampleClass.

HttpServletRequest request = null;
String path = request.getContextPath();

public void createFile() throws IOException{
File f;
f=new File(path+"WEB-INF/test.txt");
if(!f.exists()){
f.createNewFile();

}
}

my jsp is giving me this error

java.lang.NullPointerException
com.SampleClass .<init>(SampleClass.java:32)

can someone tell me what the issue is and how to fix it? I do know that I am not suppose to have request = null but what can I do to initialize it?
 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm not quite sure where to begin!

What are you hoping / trying to achieve?

The reason you are getting a null pointer for request.getContextPath() is because (as you aluded to) you have set the request to null in your class!

The normal way to instantiate an HTTPServletRequest is to get the servlet container to instantiate it for you! Then you can use the HTTPServletRequest / Response in the appropriate method of your servlet.

A JSP page also has it's own implicit request object which is available to any scriptlets which you could have used i.e.:




Then in your class remove any reference to HttpServletRequest:



etc.

HTH - Rufus.
 
reply
    Bookmark Topic Watch Topic
  • New Topic