简体   繁体   中英

difference between req.getsession().getservletcontext() and getservletcontext()

I have seen that you can call getservletcontext() directly also and also like this req.getsession().getservletcontext() .

What is the difference between the two and which one should I use ? Is there any scenario based on which I should use one and not the other?

And by the way I am using web module 2.5

What is the difference between the two

There is no difference between the two, they are one and the same.

The method getServletContext() that you can call directly is only when your code is in a class that extends HttpServlet . That is because HttpServlet base class has this method defined (actually in the GenericServlet class that HttpServlet extends).

The ServletContext returned by req.getSession().getServletContext() is same as the one returned above. HttpSession contains a reference to the ServletContext` that this session belongs to.

which one should I use? Is there any scenario based on which I should use one and not the other?

As long as your code is in the servlet class, you can use anything as both can be called.

Let's say (hypothetically) you call a method in your custom class from your servlet and pass the session object to it to work on some data in the session. This custom class doesn't extend servlet. You need a reference to the ServletContext in this custom class. Since you have a reference to the session, you can get access to the ServletContext using the method session.getServletContext() .

Hope this is clear.

The Session variables are only saved for one browser and the Context variables can be used by all browsers in one session.

So if the user only uses one browser (as it is in most cases) there is no difference between them, but if you like to work from different browsers in one session better use the Context .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM