This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Little Book of Impediments (e-book only) and have Tom Perry on-line!
See this thread for details.
Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
jo sim
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • 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?
 
Rufus Addis
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic