File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to acess servlet context variables from java class

 
chinna kumar
Greenhorn
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is my servlet:::::

ServletContext context=getServletContext();
context.setAttribute("Imsi",imsi);
context.setAttribute("Msisdn",msisdn);
context.setAttribute("Sim",sim);


now we need to access these variables from java class file raher than jsp file.
cud anyone help me out???


Chinna
 
Serghei Jelauc
Ranch Hand
Posts: 128
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do not you declare a ServletContext instance variable and create the setter method for it in your java class for example? Something like this:

public void setContext(ServletContext context) {
this.context = context;
}

After that you can use the context as usual: context.getAttribute("Sim");
 
chinna kumar
Greenhorn
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
i tried this but this does not work.

this is the modification i have done

ServletContext context;

now am trying access value using: context.getAttribute("Sim");

it says context needs to be initialized, for this is it possible to intialize without setter method as ServletContext context=getServletContext(); but this too does work..........

please help me out...
Chinna
 
Neeraj Dheer
Ranch Hand
Posts: 225
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, you can always do a context = getServletContext() without any issues.

just curious : have you over-ridden the init() method of the servlet, if yes, then have you called super.init(config) in it?
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I prefer that my beans are container unaware.
If I needed to do something like this, I would put all the variables that need to be shared into one object and bind that to context scope.
then I would pass a reference to that object to any beans that need it's properties.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic