Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ServletContext throwing Nullpointer exception  RSS feed

 
vijayakumaar ramasamy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I have one servlet class which setMessage() method as follows for global count of users accessing a site.here we want to restrict the number of users.so that we used to avoid that.



public void setMessage(String msg){
str = msg;
System.out.println("Testing of servlet in isde setMessage*************"+msg);
ServletContext context =null;
try{
context = getServletContext();
}catch(Exception e){
e.printStackTrace();
}
Integer count = (Integer)context.getAttribute("SessionCount");
if(count != null){
int ct = count.intValue();
ct++;
context.setAttribute("SessionCount",new Integer(ct));
System.out.println("Count starting from exsiting session count now the updated in the applciation scope*************"+ct);
}else{
context.setAttribute("SessionCount",new Integer(1));
System.out.println("Count starting for session user is new so now it is 1");
}

}


java.lang.NullPointerException
at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:204)
at com.panache.pcalife.action.TestServlet.setMessage(TestServlet.java:20)
at com.panache.pcalife.action.AuthenticateAction.execute(AuthenticateAction.java:109)

While accessing from the URL,ServletContext throws Nullpointer........
Please help me to overcome this problem


Regards
Vijay
 
Natarajan Shankar
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vijay,
At the point of getServletContext() what it returns, if it is not returning context handle pls. make sure that is done first.
 
vijayakumaar ramasamy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it returns Null
how should handle that?
Actaullly i need that context object.
how can i get that

vijay
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If context = getServletContext();
returns null, it is usually because you did something wrong in the servlet init method.

If you use the init( ServletConfig cnfig ) form, you MUST include the code:
super.init( cnfig ) ;
in your init method.

If you use the init() form, this is taken care of automatically.
Bill
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!