Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

servlets

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

like image 220
Nav Avatar asked Sep 16 '12 16:09

Nav


People also ask

What is request getServletContext ()?

getServletContext() method of ServletConfig interface returns the object of ServletContext. getServletContext() method of GenericServlet class returns the object of ServletContext.

What is the use of HttpSession session request getSession false?

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.

What is getServletContext in Java?

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.

What does getSession do?

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.


1 Answers

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 theServletContext` 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.

like image 86
Vikdor Avatar answered Sep 26 '22 19:09

Vikdor