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
getServletContext() method of ServletConfig interface returns the object of ServletContext. getServletContext() method of GenericServlet class returns the object of ServletContext.
If you would like to ensure that a new session object is not created by default, you can use the second form of the method: HttpSession session = request. getSession(false); If the session does not already exist, getSession(false) returns null.
Interface ServletContext. public interface ServletContext. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.
getSession() returns the valid session object associated with the request, identified in the session cookie that is encapsulated in the request object. Calling the method with no arguments creates a session if one does not exist that is associated with the request.
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.
HttpSessioncontains 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With