Amrut Dange
Amrut Dange

Reputation: 201

How to access same ServletContext object in another servlet?

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

Answers (3)

Pratik Tari
Pratik Tari

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

Siva
Siva

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

Prabhaker A
Prabhaker A

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

Related Questions