Laurent Pireyn
Laurent Pireyn

Reputation: 6875

Why do I need an HttpSession to get the ServletContext?

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?

Upvotes: 6

Views: 6301

Answers (3)

rsp
rsp

Reputation: 23383

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.

Upvotes: 8

alf
alf

Reputation: 8523

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

Upvotes: 3

djna
djna

Reputation: 55957

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.

Upvotes: 1

Related Questions