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
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 extendsHttpServlet. That is becauseHttpServletbase class has this method defined (actually in theGenericServletclass thatHttpServletextends).The
ServletContextreturned by req.getSession().getServletContext()is same as the one returned above.HttpSessioncontains a reference to theServletContext` that this session belongs to.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
ServletContextin this custom class. Since you have a reference to the session, you can get access to the ServletContext using the methodsession.getServletContext().Hope this is clear.