I am using Tomcat 6 which uses Servlet 2.5. There is a method provided in Servlet 3.0 in the ServletRequest
API which gives a handle to the ServletContext
object associated with the ServletRequest
. Is there a way to get the ServletContext
object from the ServletRequest
while using the Servlet 2.5 API?
Asked
Active
Viewed 7.8k times
44

Neel
- 2,100
- 5
- 24
- 47
1 Answers
83
You can get it by the HttpSession#getServletContext()
.
ServletContext context = request.getSession().getServletContext();
This may however unnecessarily create the session when not desired.
But when you're already sitting in an instance of the HttpServlet
class, just use the inherited GenericServlet#getServletContext()
method.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
// ...
}
Or when you're already sitting in an instance of the Filter
interface, just use FilterConfig#getServletContext()
.
private FilterConfig config;
@Override
public void init(FilterConfig config) {
this.config = config;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
ServletContext context = config.getServletContext();
// ...
}

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
And in a JSP http://stackoverflow.com/questions/2898390/java-jsp-servlet-equivalent-of-getservletcontext-from-inside-a-jsp – tgkprog Mar 03 '15 at 13:09
-
4@tgkprog: Holy, please no! – BalusC Mar 03 '15 at 13:18
-
Just to test, then put in a filter – tgkprog Mar 03 '15 at 13:28