6

In the Java Servlet API, the only way to get the ServletContext is through an instance of HttpSession (Javadoc).

What if I don't want to create a session and only need the servlet context? In other words, why is there no getServletContext() method in the HttpServletRequest class?

EDIT

I know I can get the ServletContext from the servlet itself, since it receives it during its initialization. However, I cannot get it from a HttpServletRequest alone, even though it's linked to a servlet. So what if I have a request, but no reference to any servlet?

Laurent Pireyn
  • 6,735
  • 1
  • 29
  • 39

3 Answers3

8

getServletContext() is part of GenericServlet which is the parent class for HttpServlet so you should be able to call it in your servlet implementation.

Edit:

HttpServletRequest inherits getServletContext() from ServletRequest since servlet 3.0, so it looks like you will have to pass a context along with the request and response objects if you have to use a version prior to 3.0.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
rsp
  • 23,135
  • 6
  • 55
  • 69
3

It's just that every entity working with requests (servers, filters, pages) has its own getServletContext (or init())

alf
  • 8,377
  • 24
  • 45
  • +1, however, it's not always the case. Sometimes you only have a request, and the only way to the servlet context is throught the session. – Laurent Pireyn Oct 21 '11 at 09:27
  • @LaurentPireyn e.g., when you've passed the request in further layers otherwise unaware of Servlets API? It is possible, but in this case we end up with lost of questions: whether getting `ServletContext` is a good idea in the first place; shouldn't we just push context into attributes; shouldn't we reorganize our logic; etc... – alf Oct 21 '11 at 09:40
  • I'm slipping into the "sour grapes" mode, sorry. Anyway, what is the real problem? The rationale I believe is to keep the number of methods reasonable: I'm more surprised that `getServletContext` did it into `HttpSession`. – alf Oct 21 '11 at 09:45
  • I'm also surprised, hence my question. The request has direct access to the servlet context (not through the session) since Servlet 3 (credits go to rsp for mentioning that). So it was probably something they indeed forgot. – Laurent Pireyn Oct 21 '11 at 10:23
1

Your servlet class has a getServletContext() method you don't need to go to the request.

This makes sense, the servlet itself has a context provided by the container, this is independent of any particular request.

djna
  • 54,992
  • 14
  • 74
  • 117