Reputation: 201
I have written demo program for ServletContext
object, in which I am setting value by using context.setAttribute(arg1,arg2)
. and I want to access same object in another servlet.
how can I access the value set by context object ,in another servlet.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = "Amrut";
ServletContext context = request.getServletContext();
context.setAttribute("contextuname", name);
out.println("Context==>" + context.getAttribute("contextuname"));
}
my question is, for accessing this object i have to create ServletContext
object and by using context.getAttribute(arg1,arg2)
,will i get value. or there is another value to do this.
Upvotes: 2
Views: 4489
Reputation: 198
In service(doGet/doPost) method of another servlet in same application, do this
ServletContext context = request.getServletContext();
String uName = (String)context.getAttribute("contextuname");
Upvotes: 0
Reputation: 1940
As per the Java doc
There is one context per "web application" per Java Virtual Machine.
So your Context Object will be available for all the servlets. and the attributes inside context object will also.
my question is, for accessing this object i have to create ServletContext object
It will return the same context object, it will not create a new object
Upvotes: 1
Reputation: 8483
my question is, for accessing this object i have to create ServletContext object and by using context.getAttribute(arg1,arg2) ,will i get value. or there is another value to do this.
You will get value by creating context
object same as above in the another servlet.
According to java docs
There is one context per "web application" per Java Virtual Machine.
Upvotes: 0